简体   繁体   中英

What is the purpose of creating a custom request class in laravel 5?

I downloaded a simple app which is created in Laravel 5.0. I found some files under Http\\Requests eg

Http\\Requests\\Request.php

    <?php namespace App\Http\Requests;

    use Illuminate\Foundation\Http\FormRequest;

    abstract class Request extends FormRequest {

        //

    }

Http\\Requests\\Admin\\PhotoRequest.php

<?php namespace App\Http\Requests\Admin;

use Illuminate\Foundation\Http\FormRequest;

class PhotoRequest extends FormRequest {

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'language_id' => 'required|integer',
            'photo_album_id' => 'required|integer',
        ];
    }

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

}

What is the purpose of these classes and how does it take effect?

You want to have skinny controllers for better maintainability. When you're having a lot of form fields with a lot of validation rules, your controllers will be bloated. So you need to move all data logic in models, validation logic in request classes etc.

You can read more about single responsibility principle here .

For example the rules() method, when you submit a form, it will check whether the fields is validated. In the controller you can use

function postForm(PhotoRequest $request){
    // Your Codes. You don't need to validate the data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM