Search code examples
phplaraveleloquentlaravel-5.3

How to find inverse relationship in laravel models using tinker


I got this class

namespace App;

use Illuminate\Database\Eloquent\Model;

class RetailerInfo extends Model
{

    public function user()
    {
        //same as retailer() but more consistent
        return $this->belongsTo(User::class, 'retailer_id');
    }

    public function store()
    {
        return $this->belongsTo(Store::class);
    }
}

Finding the retailer belonging to the store works just fine:

>>>namespace App;
>>>Store::find(2)->RetailerInfo
=> App\RetailerInfo {#1144
     id: 1,
     retailer_id: 65,
     store_id: 2,
     created_at: "2016-07-16 09:47:43",
     updated_at: "2016-07-16 09:47:43",
   }

but finding the user that a store belongs to doesn't work:

>>> RetailerInfo::find(1)->belongsTo(User::class)
=> Illuminate\Database\Eloquent\Relations\BelongsTo {#1176}
>>> RetailerInfo::find(1)->belongsTo(User::class, 'retailer_id')

How do I make it work?


Solution

  • As documentation says, you only need to declare the relation once, and inside a method of the model

    What you're doing with this example

    RetailerInfo::find(1)->belongsTo(User::class);
    

    Is incorrect because you don't declare relations on the go.

    Instead use the relations you already declared in your models (Store has a relation with RetailerInfo, and RetailerInfo already has a relation with User)

    Store::find(2)->RetailerInfo->user;