shops table
         Schema::create('shops', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->boolean('is_active')->default(false);
            $table->text('description')->nullable();
            $table->float('rating')->nullable();
            $table->unsignedBigInteger('location_id');
            $table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
            $table->timestamps();
        });
Here is the
shopstable. And it hasuser_idwhich is foreign key ofuserstable.
users table
         Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('photo')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->longText('cartitems')->nullable();
            $table->longText('wishlist')->nullable();
            $table->unsignedBigInteger('discount')->default(0);
            $table->rememberToken();
            $table->timestamps();
        });
This is the
userstable
Shop model (relatonship)
public function seller()    //user --> seller
{
        return $this->belongsTo(User::class, 'user_id');
}
Here I try to make a relationship between
ShopandUser
DashboardController
public function shops()
{
    $shops = Shop::all();
    dd($shops->seller()->name);
}
Here I want to get the name of the
sellerof the shop
What I am getting after run the project
BadMethodCallException Method IlluminateDatabaseEloquentCollection::seller does not exist.
Advertisement
Answer
$shops is a collection. It’s a collection of instances of Shop Model. And seller is relation of Shop Model.
foreach($shops as $shop){
    echo $shop->seller->name;
}