Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write function in laravel which needs to execute before any controller

Tags:

laravel-4

Hi i am doing a website in laravel. I am trying to do like a function that needs to execute before any controller.

Example : I have function like

function xyz(){
    //do code here
}

This function need to execute when user on site by refreshing page or doing some ajax requst.

I am aware with the codeigniter there is a way to do this using hook

$hook['pre_controller'] = array(
        'class'    => 'MyClass',
        'function' => 'Myfunction',
        'filename' => 'Myclass.php',
        'filepath' => 'hooks',
        'params'   => array('beer', 'wine', 'snacks')
);

What is the way in laravel to do this ?

like image 375
Kango Avatar asked Dec 05 '25 14:12

Kango


1 Answers

You can use Laravel Middleware to achieve this. The middleware can be registered as global for all controllers / routes, and will let you execute that function (or you can register it for subset of routes by using router groups).

Example:

<?php

namespace App\Http\Middleware;

use Closure;

class MyMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // call your function
        $this->xyz();

        return $next($request);
    }

    public function xyz()
    {
        // do something
    }
}

See the Laravel documentation on Middleware.

like image 69
Niraj Shah Avatar answered Dec 09 '25 18:12

Niraj Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!