Laravel not getting Accessor within a map collection
Laravel not getting Accessor within a map collection
I'm trying to get the value of a map object to check if a user made a rating or not.
{{ $book->rated }}
is returning neither false or true.
{{ $book->rated }}
This method needs to get the type of the rating, the default value is set to false
public function getTypeAttribute(){
return Rate::where('type', $this->attributes['id'])->where('user_id',auth()->user()->id) === self::RATED;
}
Book.php
use IlluminateDatabaseEloquentModel;
use willvincentRateableRateable;
use AppUser;
use AppRate;
class Book extends Model
{
use Rateable;
const RATED = "true";
const NOT_RATED = "false";
protected $fillable = [ 'user_id', 'title', 'description'];
public function scopeGetBook($query, $book_name )
{
return $query->where('slug', $book_name );
}
public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
$this->attributes['slug'] = str_slug($value);
}
public function scopeGetBookUser($query, $user_id)
{
return $query->where('user_id', $user_id )->first();
}
public function getTypeAttribute(){
return Rate::where('type', $this->attributes['id'])->where('user_id',Auth()->user()->id) === self::RATED;
}
Rate.php
<?php
namespace App;
use AppUser;
use IlluminateDatabaseEloquentModel;
use willvincentRateableRateable;
class Rate extends Model
{
protected $fillable = [
'user_id',
'type',
'rating'
];
public $timestamps = false;
protected $table = 'ratings';
}
BookController.php (this is how the type is being set, and how im trying to retrieve the value)
public function rate(Request $request, $book_id)
{
$book = Book::find($book_id);
$rating = $book->ratings()->where('user_id', auth()->user()->id)->first();
if(is_null($rating)){
$ratings = new Rating();
$ratings->rating = $request['rating'];
$ratings->user_id = auth()->user()->id;
$ratings->type = Book::RATED;
$book->ratings()->save($ratings);
return json_encode($book);
}
else{
return response()->json(['status' => 'You already left a review']);
}
}
public function show($book_name)
{
$books = Book::with('ratings')->GetBook($book_name)->get();
$data = $books->map(function(Book $book){
$book['rated'] = $book->getTypeAttribute();
return $book;
});
return view('books.show', compact('data', $data));
}
HTML
<div id="rateYo" data-rateyo-rating="{{ $book->userSumRating or 0}}" data-rateyo-read-only="{{ $book->rated }}" > ></div>
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.