D
D
devkornev2019-01-07 12:51:50
Validation
devkornev, 2019-01-07 12:51:50

Form validation in Laravel 5, how to make it easier and more correct?

I'm learning Laravel and trying to work out for myself a convenient way to validate forms. I would like the rules to be written for each model only once and it would be possible to conveniently access these rules from the controller. I did it in the following way, it works, but I'm not sure if it's beautiful and optimal. Can Laravel, as usual, offer something simpler and prettier for this?
Model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    const STATUS_DISABLE  =  0;
    const STATUS_ENABLE   = 10;

    // Разрешенные поля, необходимо при использовании create($request->all()).
    protected $fillable = ['title', 'slug', 'description', 'parent_id', 'status'];

    // Правила валидации.
    public static function rules() {
        return [
            'title'         => 'required|max:32',
            'slug'          => 'required|unique:categories|max:32',
            'parent_id'     => 'required|integer',
            'status'        => 'required|integer|in:' . implode(',', array_keys(self::getStatusesExisting())),
            'description'   => 'max:255',
        ];
    }

    // Массив статусов.
    public static function getStatusesExisting() {
        return [
            self::STATUS_DISABLE => 'Отключена',
            self::STATUS_ENABLE  => 'Активна'
        ];
    }

    // Дочерняя категория.
    public function children() {
        return $this->hasMany(self::class, 'parent_id');
        
    }
}

Controller:
namespace App\Http\Controllers\Backend;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{

...

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Валидация.
        $request->validate(Category::rules());

        // Запись.
        Category::create($request->all());

        // Возврат к списку.
        return redirect()->route('backend.category.index');
    }

...

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        // Валидация.
        $request->validate(Category::rules());

        // Обновление.
        $category->update($request->all());

        // Возврат к списку.
        return redirect()->route('backend.category.index');
    }

...

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2019-01-07
@devkornev

I want the rules to be written for each model only once
In the general case, this is an incorrect desire - the validation rules can radically differ for the element editing form in the user's account and in the admin panel. There may be different sets of fields, different requirements for each field, its own obligation.
Well, in general, the model has nothing to do with validation.
Therefore, it is not the model that is validated, but queries . Create a Request Form for your request and describe all the rules there. Then it will be possible to inherit from it for other similar queries or create independent ones.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question