Blagoh
Blagoh

Reputation: 1235

Unable to use `lists` in many to many relationship

My Laravel version is 5.5.13.

I created a many to many relationship between User model and Pet model. Pets can belong to multiple users.

I am trying to do in my update method in controller, get a list of all associated user ids. So I tried:

public function update(Request $request, Pet $pet)
{
    dd($pet->users()->lists('id'));
    $pet->update($request->all());
    return response()->json($pet, 200);
}

However I get:

Call to undefined method Illuminate\Database\Query\Builder::lists()

It seems there is no lists().

If I do dd($pet->users()) it gives no error and shows a lot of information.

*May you please help to get this lists() to work.

My relationship in Pet model is:

public function users()
{
    return $this->belongsToMany('App\User');
}

And my relatinship in User model is:

public function pets()
{
    return $this->belongsToMany('App\Pet');
}

Here is my migration for the pivot:

Schema::create('pet_user', function (Blueprint $table) {
    $table->integer('pet_id')->unsigned()->index();
    $table->foreign('pet_id')->references('id')->on('pets')->onDelete('cascade');

    $table->integer('user_id')->unsigned()->index();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

    $table->timestamps();
});

Upvotes: 0

Views: 38

Answers (2)

Arpita
Arpita

Reputation: 1398

laravel has deprecated the lists() method use pluck instead.

https://laracasts.com/discuss/channels/laravel/lists-deprecated-replacement

Upvotes: 1

Mr. Pyramid
Mr. Pyramid

Reputation: 3935

list() is no more available in Laravel. Alternatively you can use pluck() and pluck all items like this pluck()->all();

pluck('key')->all();
pluck()->all();

Reference doc

Upvotes: 1

Related Questions