Search code examples
laravelvalidationlaravel-5.3rules

How to add laravel validation for updates only once?


My function to update like this :

public function updateRating(UpdateRatingRequest $request) {
    $param = $request->only('id', 'rating');
    $id = $param['id'];
    $rating = $param['rating'];
    $review = Review::find($id);
    $review->rating = $rating;
    $review->save();
}

My validation rules like this :

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateRatingRequest extends FormRequest {
    public function rules() {
        return [
            'id'=>'required',
            'rating'=>'required'
        ];
    }
}

I want to add validation server side laravel. If a particular id column, the rating column has been updated, it can not be updated again. So every id, its rating column can only be updated once

For example I have id = 8. if on the id = 8, the rating column has been updated. Then the rating column at id = 8 can not be updated again. So it can only be updated once

How can I do it?

Update

This is my way of checking id that has a null rating with mongodb :

$reviews = Review::where('_id',$param['id'])->whereNull('rating')->first();

The process is the same as laravel


Solution

  • As you have said in the comments that the rating value is null beforehand you could use the exists validation rule:

    public function rules()
    {
        return [
            'id'     => [
                'required',
                Rule::exists('reviews')->where(function ($query){
                    $query->whereNull('rating');
                })
            ],
            'rating' => 'required',
        ];
    }
    

    Please note you will have to include the use statement for the Rule facade in your UpdateRatingRequest class:

    use Illuminate\Validation\Rule;
    

    Hope this helps!