hkguile
hkguile

Reputation: 4369

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 e.g.

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?

Upvotes: 4

Views: 1600

Answers (2)

Specs
Specs

Reputation: 103

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
}

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163848

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.

Upvotes: 4

Related Questions