Show some code?
Jan 24, 2023
6
Level 1
Where to add logic validation
I am having an endpoint that submits a user's rating for a salon. I want to validate that one user can only have one rating for a salon.
In which layer am i supposed to put this validation logic? Are policies a valid option or are they only used for authorization validation?
Here are the models
class Salon extends Model
{
use HasFactory;
protected $fillable = ['name', 'phone', 'email', 'address', 'type', 'lat', 'lng', 'active_code', 'is_active'];
public function ratings()
{
return $this->morphMany(Rating::class, 'model');
}
}
class Rating extends Model
{
use HasFactory;
protected $fillable = ['client_id', 'model_type', 'model_id', 'rating', 'comment'];
public function save(array $options = [])
{
if (!$this->client_id) {
$this->client_id = auth()->user()->id;
}
return parent::save($options);
}
public function model()
{
return $this->morphTo();
}
public function client()
{
return $this->belongsTo(Client::class);
}
}
class Client extends Authenticatable
{
use HasFactory, HasApiTokens;
protected $fillable = ['name', 'email', 'phone', 'gender', 'birthdate', 'password', 'type', 'address', 'lat', 'lng', 'verification_code', 'verified', 'latest_verification_code'];
protected $casts = [
'birthdate' => 'date'
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function ratings()
{
return $this-morphMany(Rating::class,'model');
}
}
This is the controller
class RateSalonController extends Controller
{
public function store(RateSalonRequest $request)
{
$salon = Salon::find($request->salon_id);
$salon->ratings()->create($request->validated());
return apiResponse(['message' => 'Rating submitted successfully!'], Response::HTTP_OK);
}
}
Level 51
if you add this to your Salon model (and again this is prime for a trait for ratings...)
public function voters()
{
return $this->ratings->map->client;
}
then your logic can be
public function passes($attribute, $salonId)
{
return Salon::find($salonId)
->voters()->doesntContain(auth()->user());
}
and now you have a method for $salon->voters() too
1 like
Please or to participate in this conversation.