Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Querying a many to many relationship without "pivot" in the result

I have the following tables

  • users
    • id
  • books
    • id
  • favourite_books
    • id
    • user_id (FK)
    • book_id (FK)

I have the following Model:

class User {
    public function favouriteBooks()
    {
        return $this->belongsToMany(Book::class, 'favourite_books');
    }
}

I want to get all the ids that belong to a user.

The way I am doing this currently is like so:

$user->favouriteBooks()->select('book_id')->get();

However this returns data like so;

[
   {
     "book_id": 23,
     "pivot": {
       "user_id": 57,
       "book_id": 23
     }
   },
   {
     "book_id": 41,
     "pivot": {
       "user_id": 57,
       "book_id": 41
     }
   },
   ...
]

I want it to return data like so:

[
   23,
   41,
   ...
]

How can I do that?

like image 710
Yahya Uddin Avatar asked Apr 21 '17 19:04

Yahya Uddin


People also ask

How do I delete a pivot table in Laravel?

To delete all records on the pivot table for a model, you may use the detach method: User::find(1)->roles()->detach();

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

What is BelongsTo in Laravel?

BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.


2 Answers

I recommend putting pivot in the hidden array like in user.php:

protected $hidden = ['pivot'];

which would remove pivot from all json's returned.

like image 84
Hazem Emad Avatar answered Oct 26 '22 06:10

Hazem Emad


Use the pluck() method:

$user->favouriteBooks()->pluck('book_id');
like image 12
Alexey Mezenin Avatar answered Oct 26 '22 07:10

Alexey Mezenin