mercredi 30 janvier 2019

laravel custom validation rule when updating record

I have 2 tables for Series and Lessons in lessons Model I have relation to relate lesson to a series, I created a custom validation rule to prevent the same episode_number in the lessons table to be repeated in the same series and it works fine but when updating I want to exclude this lesson from being checked This is my table of lessons

public function up()
{
    Schema::create('lessons', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('series_id');
        $table->string('title');
        $table->text('description');
        $table->unsignedInteger('episode_number');
        $table->unsignedInteger('video_id')->unique();
        $table->boolean('premium')->default(0);
        $table->timestamps();

        $table->unique(['series_id', 'episode_number']);
    });
}

and this is the eloquent relation function in lessons model

public function series()
{
    return $this->belongsTo(Series::class);
}

and here is my custom validation rule

<?php
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\DB;

class uniqueSeriesLessonValidation implements Rule
{
public $id;
/**
 * Create a new rule instance.
 *
 * @return void
 */
public function __construct($id)
{
    $this->id = $id;
}

/**
 * Determine if the validation rule passes.
 *
 * @param  string  $attribute
 * @param  mixed  $value
 * @return bool
 */
public function passes($attribute, $value)
{
    $count = DB::table('lessons')->where('episode_number', $value)
        ->where('series_id', $this->id)
        ->count();

    if ($count === 0){
        return true;
    }

    return false;

}

/**
 * Get the validation error message.
 *
 * @return string
 */
public function message()
{
    return 'The lesson title should not be repeated in the same series twice.';
}
}

and this is my validation when creating new lesson which works fine to prevent duplicate of episode_number of a lesson in the same series twice

public function rules(Request $request)
{
    return [
        'title' => 'required',
        'description' => 'required',
        'episode_number' => ['required',new uniqueSeriesLessonValidation($request->series_by_id->id)],
        'video_id' => 'required|unique:lessons|numeric'
    ];
}

and this is my validation when updating lesson which I have the problem

public function rules(Request $request)
{
    return [
        'title' => 'required',
        'description' => 'required',
        'episode_number' => ['required',new uniqueSeriesLessonValidation($request->series_by_id->id),$request->lesson->id],
        'video_id' => 'required'
    ];
}



from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2TlAJAJ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire