Catch TokenMismatchException thrown by VerifyCsrfToken in Laravel

Reading Time: 2 minutes

If you are using Laravel 5, you must have come across something like this when a form wasn’t after a long period of time of opening the page.

 

This was meant to help with checking against CSRF but it can be really annoying seeing this. Most of your user/visitors don’t understand the gibberish written, and you can’t possibly tell them to always submit the forms on time. No, you just can’t. Neither should you assume that they will only be visiting your website/app at the time they are on the page.

Solution

Don’t disable the CSRF verification on your site. DON’T!

You can just simply catch this error and do something with it (well, not literarily).

Let me show you how you can catch the error and possible display the form again.

  1. Open app/Exceptions/Handler.php
  2. Find the render() method
  3. Add this piece of code to it

     

    if ($exception instanceof TokenMismatchException){
        //redirect to a form. Here is an example of how I handle mine
        return redirect($request->fullUrl())->with('flash-msg', 'Oops! Seems you didn\'t submit form for a longtime. Please try again.');
    }
  4. So your render method should now look like this

     

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof TokenMismatchException){
            //redirect to a form. Here is an example of how I handle mine
            return redirect($request->fullUrl())->with('flash-msg', 'Oops! Seems you didn\'t submit form for a longtime. Please try again.');
        }
        return parent::render($request, $exception);
    }

You can decide to do something else instead of redirecting to the original form.

That, my friend, is how to overcome the ugly TokenMismatchException in VerifyCsrfToken.php without compromising your site’s security.

Update

If you cannot find the render() method, go to vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php

Copy the render() method and paste it in app/Exceptions/Handler.php

Replace $exception with $e

So your final render() method in app/Exceptions/Handler.php will look like this

public function render($request, Throwable $e)
    {
        if (method_exists($e, 'render') && $response = $e->render($request)) {
            return Router::toResponse($request, $response);
        } elseif ($e instanceof Responsable) {
            return $e->toResponse($request);
        }

        $e = $this->prepareException($this->mapException($e));

        foreach ($this->renderCallbacks as $renderCallback) {
            if (is_a($e, $this->firstClosureParameterType($renderCallback))) {
                $response = $renderCallback($e, $request);

                if (! is_null($response)) {
                    return $response;
                }
            }
        }

        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof AuthenticationException) {
            return $this->unauthenticated($request, $e);
        } elseif ($e instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($e, $request);
        } elseif ($e instanceof TokenMismatchException){
            return redirect($request->fullUrl());
        }

        return $request->expectsJson()
            ? $this->prepareJsonResponse($request, $e)
            : $this->prepareResponse($request, $e);
    }
 

Bind multiple models to a form in Laravel 5 and validate it

Reading Time: 3 minutesForm model binding in Laravel 5 makes the programmers’ live easier, no doubt. But what if you want to bind multiple models to a form? This is not straight forward but it’s not so complex either. (May be it was till I cracked it)

Follow the steps below and you should be okay.

Note:

  • I am assuming that there is a one on one relationship between the models you are binding.
  • Form model binding works if you have Laravel Collective’s Form & HTML package installed in your project.

 

Creating the Form Controller Method

First of all, create the controller method, and pass the model to the view.

class MyProfileController extends Controller
{
    public function edit(){
        $data = [
            'user' => User::find(Auth::user()->id), //Pass the model as data
            'pageTitle' => 'Edit my profile',
        ];
        return view('profiles.edit', $data);
    }
}

In the above example, the User model has a relationship with the other models we are binding to the form.

 

Defining the relationships in the Models

The models need to be related for this method to work. In our case, we are working with User model and Profile models.

The User model

The user model was created using the artisan make:auth command but this doesn’t matter. It can as well be a child of the Model class

class User extends Authenticatable
{

    //
    //...
    //
    public function profile(){
        return $this->hasOne('App\Profile');
    }
}

 

The Profile model

This is the reverse in the one one one relationship

class Profile extends Model
{
    
    //
    //...
    // 


    public function user(){
        return $this->belongsTo('App\User');
    }
}

 

The View, where the Form Model binging takes place

Like I mentioned, form model binding works with Laravel Collective’s Form & HTML package. So here is what the view looks like

{!! Form::model($user, ['url' => url('profile/edit')]) !!}
            {!! csrf_field() !!}



            <!-- name field -->
            <div class="form-group  {{ $errors->has('name') ? ' has-error' : '' }}">
                {{ Form::label('name', 'Full name') }}
                {{ Form::text('name', null, ['id'=>'name', 'placeholder'=>'Your full name', 'class'=>"form-control"]) }}

                @if ($errors->has('name'))
                    <span class="help-block">{{ $errors->first('name') }}</span>
                @endif
            </div>

            <!-- About Me field -->
            <div class="form-group  {{ $errors->has('profile.about_me') ? ' has-error' : '' }}">
                {{ Form::label('about_me', 'About me') }}
                {{ Form::textarea('profile[about_me]', null, ['id'=>'about_me', 'placeholder'=>'A little info about you', 'class'=>"form-control", 'rows' => 4]) }}

                @if ($errors->has('profile.about_me'))
                    <span class="help-block">{{ $errors->first('profile.about_me') }}</span>
                @endif
            </div>

            <!-- city field -->
            <div class="form-group  {{ $errors->has('profile.city') ? ' has-error' : '' }}">
                {{ Form::label('city', 'Town/City   ') }}
                {{ Form::text('profile[city]', $value = null, ['id'=>'city', 'placeholder'=>'Your town or city of residence', 'class'=>"form-control"]) }}

                @if ($errors->has('profile.city'))
                    <span class="help-block">{{ $errors->first('profile.city') }}</span>
                @endif
            </div>

         

            <button class="btn btn-info btn-md" type="submit">
                <i class="fa fa-save"></i>
                Save profile
            </button>

            {!! Form::close() !!}

 

Take note

  • The name field belongs to the User model while the about_me and city fields belong to the Profile model
  • Dot notation is used for the error names of the Profile fields/properties e.g profile.city while the name of the form field uses [ ]  e.g profile[city] (No quotation marks)

 

Writing the Validation logic

We need to validate the 3 fields i.e

  1. name
  2. about_me
  3. city

There are a number of ways to write the validation logic. I usually prefer to create a Request. This allows for reuse.

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

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

        return [
            'name' => 'required|max:40|min:3',
            'profile.about_me' => 'required|max:500',
            'profile.city' => 'max:40|min:2',
        ];

    }

    public function messages()
    {
        return [
            'required' => 'This field is required',
            'min' => 'Must not be less than :min characters',
            'max' => 'Must not be greater than :max characters'
        ];
    }
}

In the rules() method, notice that I used the dot notation for about_me and city properties.

You need to create/override the messages() method and define custom messages, if not your users will see gibberish arising from :attribute property used in the default message which will make return something like “The profile.about_me field is required

 

Saving the form fields

You can go ahead and save the form fields. You don’t have to use the [] or dot notations, Request will recognise the form fields (i.e name, about_me and city) the way they are.

 

Conclusion

This process is pretty straightforward like I mentioned earlier. Go ahead and give it a try. And if you have any questions, use the comment section below.

 

How to prevent Android’s RecyclerView from recycling views

Reading Time: < 1 minuteThe RecyclerView widget, alongside the CardView widget, was introduced in Android API 21 (Lollipop). RecyclerView is a more flexible and more advanced version of ListView, according to Android developers’ website. But don’t read flexible as easier to implement. It’s cool though. yeah, it’s ListView on steroids.

One of its key feature is that it recycles views that are out of device screen. It is a cool feature but it’s not always a good thing. There are times you don’t really want to recycle views. Or when recycling messes up your display.

To overcome that, you have to take advantage of the setIsRecyclable() of the RecyclerView.ViewHolder class. Take a look at the onBindViewHolder() method to see how I solved implemented this.

@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    final DataSource dataSource = dataSourceList.get(position);

    holder.setIsRecyclable(false);

    holder.name.setText(dataSource.getName());
    holder.active.setChecked(dataSource.getActive());

    String logoStr = dataSource.getLogo();

    //Logo
    /**
     * Do all the logo insertion stunts here
     */
    /**
     * Register the changes to the Switch
     */
    holder.active.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
            dataSource.setActive(isChecked);
        }
    });
}

You can argue that this is going against what RecyclerView was designed to do, but then remember that Google themselves must have considered that recycling might not always be a desired result, hence they created a shortcut.

Hope this works for you.

 

P.S.: If you have any issues or questions, don’t hesitate to ask questions via the comments below. I will try to answer as many as I can. Well, you can also talk about anything related too. No, no spamming please

P.P.S.: if you want to learn how to work with RecyclerView, I recommend a very good tutorial on AndroidHive.info

 

How to create custom helper functions in Laravel 5

Reading Time: 2 minutesCreating simple PHP helper functions in Laravel 5 is not really something that comes out of the box, unlike what is obtained in CodeIgniter. This is one of the very few things I initially missed when I switched from CodeIgniter to Laravel.

However, there is a short solution. This might not necessarily be in compliance with Laravel’s best practices, but I kinda like it. Besides, it’s pretty straight forward.

Follow these three steps and you are good to go.

1. Create a Helper’s folder

Go to your app folder, create a new folder and name it Helpers. Helpers should be a sub folder of the app folder. This folder will be where all your helper function files will reside.

You can group related functions in the same script. This is one more reason I like this approach rather than creating one long file with all the helper functions (which will get harder to maintain as you add more functions)

2. Create a Service Provider

Create a Laravel Service Provider to handle your helper scripts and functions. You can do that manually or just use the artisan CLI command.

php artisan make:provider HelperServiceProvider

In the above, the Service Provider is called HelperServiceProvider.

Service Providers in Laravel have two methods ie the boot() and the register() methods. We are going to leave the boot() method empty, we only need the register() method. Add the following code to the register() method of the Service Provider you created.

public function register()
{
    foreach (glob(app_path().'/Helpers/*.php') as $filename){
        require_once($filename);
    }
}

3. Register your Service Provider

The last step involves registering your Service Provider in your application’s app config file ie config/app.php

Got to the providers section/element of the array and add the following

App\Providers\HelperServiceProvider::class,

So your providers section should look like this

'providers' => [
    //
    // Other Service providers listed here...
    //

    App\Providers\HelperServiceProvider::class,
];

Next steps

You can now start creating your functions in files in the Helpers sub folder of the app folder. You don’t have to follow any rules in naming your files. But I like to end mine with Helper.php so as to make them easily searchable for me.

Note that the helper files are just simple PHP scripts and not classes. So you can create a new function using the following syntax

if(!function_exists('exampleFunction')){
    /**
     * Doc block of function defined
     * @param type $symbol
     * @return 
     */
    function exampleFunction($param){
        //
        //Function code here
        //
    }
}

And whenever you want to call your functions, just do it the normal PHP way ie exampleFunction()

That’s all folks!

 

 

Note:

  • This code was tested with Laravel 5.2
  • You can change the name of the Service Provider file and that of the helper folder, it will still work so long as you are consistent.