Article

Request based form validation with Laravel

August 09, 2017  |  Code School
Learn something new. Take control of your career.
Sign up

So you want to build an app from scratch, but don’t have time? PHP’s Laravel framework could be the answer, offering several helpful components right out of the box. Whether you’ve learned the why of using Laravel with our Try Laravel course or our previous post, it’s time to dig into a practical use case of this PHP framework. 

When we left off with our application in Try Laravel, we were using basic validation that looks like this:

 /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:markets|max:255',
            'website' => 'required',
            'city' => 'required',
        ]);
        
        Market::create($request->all());
        return redirect('markets')->with('status', 'New Market Created!');
    }

In this example we are using a standard validator on the request object, then applying rules to each of our form inputs. If this passes the rules we set up then we will create our new Market and redirect back to the markets index page. This type of system works fine when we have a couple of fields, but when our form grows, so will our validation. We want to also keep our code clean and reusable, for instance when we will need to call the same validation from our edit action.

We will handle this by using a custom Form Request Validation which we will need to generate. To accomplish this you will want to run the artisan make:request command followed by the name of the request.

    php artisan make:request StoreMarket

Once the new class is generated you will find it in the app/Http/Requests directory. Let's take a look at our new class: 

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

Since we have not set up authentication in our application just yet we will need to change the first method return value to true. This way anyone is authorized to create a market. Clearly we would not want to put this in to production without authentication, but for now we will just bypass this logic.

The next method is the rules method, lets add the rules from our existing code to this method.

/**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'name' => 'required|unique:markets|max:255',
          'website' => 'required',
          'city' => 'required',
        ];
    }

Now that we have the rules in our new form request class, we will need to implement this in our controller to apply these rules.

We will need to do a few things to make this work as it does now in the controller. First we will remove the type-hinting for 'Request' in the store argument and replace it with our new class 'StoreMarket' leaving $request as is. This will use our for request instead and apply the rules in our custom class. In order for the controller to see our new request we will have to add its namespace at the top of our file, just under the call to the Request class

use App\Market;

use Illuminate\Http\Request;

use App\Http\Requests\StoreMarket;

The final thing that will need to happen is to remove the existing call to $this->validate, as it will now be handled by the custom request.

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreMarket $request)
    {
        Market::create($request->all());
        return redirect('markets')->with('status', 'New Market Created!');
    }

Now if a validation fails, a redirected response will be generated to redirect back to the form. Also, just as before, any errors will also be flashed to the session and displayed to the user.

If you want to learn more about this, you can read up on the Laravel docs on their website. To really dive into what can be done with Laravel, try out our new course, From Form to Table With Laravel. 

Learn something new. Take control of your career.
Sign up

Code School

Code School is an on-demand learning destination for existing and aspiring developers. Each course is built around a creative theme and... See more