Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Laravel 5: Apply a piece of code to every request

Sometimes this is approached using inheritance (overriding), or some kind of hook concept. This can also be done with middleware in Laravel 5.

For a slightly contrived and brief example: Imagine you need to apply some custom settings to all requests, but you don’t want to write these settings permanently to the filesystem for use cases where it does not make sense to do so. In this example, we dynamically set the email provider.

Create a file in app/Http/Middleware/ApplySettings.php:

namespace App\Http\Middleware;

use Closure;
use Settings;

class ApplySettings
    const PROVIDER_MAILGUN = "mailgun";
    const PROVIDER_MANDRILL = "mandrill";

     * Run the request filter.
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
    public function handle($request, Closure $next)
        if(Auth::check()) {
            $settings = Settings::getSettings2();
            $emailProviderStr = $settings->email_provider;
        return $next($request);

    private function setEmailProvider($providerStr) {

        if($providerStr==self::PROVIDER_MAILGUN) {

            config(['mail.driver' => self::PROVIDER_MAILGUN]);
            config(['services.mailgun.domain' => '']);
            config(['services.mailgun.secret' => 'hum[email protected]']);

        } else if($providerStr==self::PROVIDER_MANDRILL) {

            config(['mail.driver' => self::PROVIDER_MAILGUN]);
            config(['services.mandrill.secret' => '[email protected]']);


And don’t forget to include in Kernel.php the line to activate our middleware:

Notice that the settings retrieval is wrapped inside of an Auth check. That is because the user may not be logged in at the time, and we need to handle that instead of let the application crash.

Now let’s imagine that mail is sent later in the request lifecycle after this code has run. Then Laravel’s Mail will use the setting that was set.

This post first appeared on Ninjamedia Web Development, please read the originial post: here

Share the post

Laravel 5: Apply a piece of code to every request


Subscribe to Ninjamedia Web Development

Get updates delivered right to your inbox!

Thank you for your subscription