Access route parameters in a Laravel 5 Middleware

In Laravel, when you specify your routes, you can place parameters in the URL. These parameters can also be automatically mapped to Model objects.

For example, you have a root where the path looks like this: /forum/{forumModel}/edit.

If you are writing a Middleware that should check something on the request and you need to access the parameter (forumModel in our case) in the URL, you can just do this:

<?php

class SampleMiddleware {

    /* ... */

    public function handle($request, Closure $next)
    {
        $forumModel = $request->forumModel;

        /* Do some stuff... */

        return $next($request);
    }

}

That’s it, the route parameters are accessible directly from the $request object.

Store who created and last updated a record in Laravel 4

Laravel provides a very handy way to store who created and last updated a given row in the database. Actually there are two very similar ways you can implement this.

The basic idea is that model events allow you to perform actions when a model object is created, updated, deleted and so on.  We will use these events to perform the saving of the user who created or updated the given row.AAEAAQAAAAAAAAblAAAAJGRmY2NjYjVhLTk2MDctNGMxYi1hYmYyLWM0MTkxNjRjYWQ5OQ

1. Model events in the global scope

Using model events you can specifiy code blocks that will run in case of different events that a model object fires.

<?php

Forum::creating(function($forum)
{
    $forum->created_by = Auth::user()->id;
    $forum->updated_by = Auth::user()->id;
});

Forum::updating(function($forum)
{
    $forum->updated_by = Auth::user()->id;
});

You can specify these model events for example in the same php file where your model resides, but outside of the class definition.

2. Model events inside the boot function of a model

The second option is similar in effect to the first one. It works by overriding the boot function of the model and through static methods provide the functions the will run when the model object is created or updated. Here is an example of that:

<?php

class Forum extends Eloquent {

    //...

    public static function boot()
    {
        parent::boot();

        static::creating(function($forum)
        {
            $forum->created_by = Auth::user()->id;
            $forum->updated_by = Auth::user()->id;
        });

        static::updating(function($forum)
        {
            $forum->updated_by = Auth::user()->id;
        });
    }
}

You can see that when a model object is created we update both the created_by and updated_by columns, because in this case the updating event won’t fire. In case of an update to an existing record, the updating event will fire so we are specifying the code for setting the updated_by colum value there. This example assumes that you are using Laravel’s authentication metod, because we are using that to get the user who is currently logged in, and then it’s id.