Skip to content
Advertisement

How can I get the foreign-key name of `user` of `users` table using `Shop` model in laravel?

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 shops table. And it has user_id which is foreign key of users table.

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 users table

Shop model (relatonship)

public function seller()    //user --> seller
{
        return $this->belongsTo(User::class, 'user_id');
}

Here I try to make a relationship between Shop and User

DashboardController

public function shops()
{
    $shops = Shop::all();

    dd($shops->seller()->name);
}

Here I want to get the name of the seller of 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;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement