ldc-legaulois/app/Models/Customers.php
Jérémy Munsch dede5a81ff Recipe Rating and Customer auth conditions
- fix on recipes.show rate function
-  rate step to 0.5
 -  show user rate instead of global rate
 - add rating to customer recipe pivot table
 - add condition on recipes for auth customer
 - save recipe rating for customer if auth
2021-02-19 19:05:06 +01:00

75 lines
1.7 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Customers extends Authenticatable
{
use Notifiable;
protected $guard = 'customer';
public function recipes()
{
return $this->belongsToMany(Recipes::class, 'customers_recipes', 'customer_id', 'recipe_id');
}
public function products()
{
return $this->belongsToMany(Products::class, 'cart');
}
public function forums()
{
return $this->hasMany(Forum::class);
}
public function answers()
{
return $this->hasMany(ForumAnswers::class);
}
/**
* Check if Customer has a recipe in favorites
*
* @param Recipes $recipe
* @return boolean
*/
public function hasRecipe(Recipes $recipe)
{
return $this->recipes()->find($recipe) ? true : false;
}
/**
* Set the rating for this customer
*
* @param Recipes $recipe
* @return float|null
*/
public function getRecipeRating(Recipes $recipe)
{
$recipe = $this->recipes()->withPivot('rating')->find($recipe);
return $recipe->pivot->rating ?? null;
}
/**
* Set the rating for this customer
*
* @param Recipes $recipe
* @param float $rating
* @return bool
*/
public function setRecipeRating(Recipes $recipe, float $rating)
{
/** @var \Illuminate\Database\Eloquent\Relations\Pivot $p */
$p = $this->recipes()->find($recipe);
if (!$p) {
return (bool)count($this->recipes()->syncWithoutDetaching([$recipe->id => ['rating' => $rating]]));
} else {
$p->pivot->rating = $rating;
return $p->save();
}
}
}