I am building a Laravel Application where people read book, favorite the book also.
Book Resource
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
'about' => $this->about,
'content' => $this->content,
'image' => $this->image_url,
'recommended' => $this->recommended,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'author' => $this->author,
'no_of_pages' => $this->pages,
// 'favorited' => I want o show true or false depending if user favorited
];
}
I want to set include Favorited Book by the user in the user model, so it shows true if the user has favorited and false.
I was able to do it in a single book model, by doing this
public function showapi(Request $request, $book)
{
//$book = Book::find($book);
$book = new BookResource(Book::find($book));
$Fav = Favorite::where('book_id', $book->id)->where('user_id', $request->user_id)->exists();
if($Fav) {
return response()->json([
'book' => $book,
'Favorited' => $Fav,
]
);
}
else
return response()->json([
'book' => $book,
'Favorited' => $Fav,
]
);
}
This set Favorited to True or False
But I want to show Favorited when I send the collection of Books
I have tried using Laravel API Resource Relationship by doing this
'item' => FavoriteResource::collection($this->when(Favorite::where('book_id', $this->id)
->where('user_id', $request->user_id), 'item')),
I got this error while using postman to test
Call to a member function first() on string in file
This is my method
public function indexapi()
{
return BookResource::collection(Book::with('author')->Paginate(16));
}
This is my relationship
User Model
public function favorites(){
return $this->hasMany(Favorite::class);
}
public function books()
{
return $this->belongsToMany(Book::class);
}
Book Model
public function favorites()
{
return $this->hasMany(Favorite::class);
}
** Favorite Model **
public function book ()
{
return $this->belongsTo(Book::class);
}
public function author()
{
return $this->belongsTo(Author::class);
}
public function user()
{
return $this->belongsTo(User::class);
}