Reputation: 2160
I have 3 models called Customer,Receiver and Legal. Each model can have only one card and I have created a Model called Card.
this is my cards table in database
id | cardable_id | cardable_type | number | ...
--------------------------------------------------------------------
1 | 1 | Receiver | 6221-0612-0410-4907 | ...
2 | 5 | Customer | 6301-4569-7896-4563 | ...
3 | 2 | Legal | 6748-8520-4569-9630 | ...
My Card Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Card extends Model
{
public function cardable()
{
return $this->morphTo();
}
}
My Customer Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
public function card()
{
return $this->morphOne(Card::class,'cardable');
}
}
My Legal Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Legal extends Model
{
public function card()
{
return $this->morphOne(Card::class,'cardable');
}
}
And My Receiver Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Receiver extends Model
{
protected $guarded = ['id'];
public function card()
{
return $this->morphOne(Card::class,'cardable');
}
}
In my routs in web.php for testing relations I wrote the code below:
Route::get('test',function () {
$card = \App\Card::find(1);
return $card->cardable;
});
and I faced following error:
Class 'Receiver' Not found.
And when I try to use inverse relation:
Route::get('test2',function () {
$customer = \App\Customer::find(5); // a customer with id=5 does exist
return $customer->card;
});
it returns null.
I'm trying to get an instance of card's owner using $card->cardable
and also get an instance of card using $customer->card
or $receiver->card
or $legal->card
What am I missing? Is this the right relation I have chosen for my purpose?
Upvotes: 1
Views: 84