I have the following tables
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?
To delete all records on the pivot table for a model, you may use the detach method: User::find(1)->roles()->detach();
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.
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.
I recommend putting pivot in the hidden array like in user.php:
protected $hidden = ['pivot'];
which would remove pivot from all json's returned.
Use the pluck()
method:
$user->favouriteBooks()->pluck('book_id');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With