How to Get Current Controller Name in View Laravel?

Today now in this post i will show you How to Get Current Controller Name in View Laravel? Sometimes If you need to get the current controller name in your view file or need to know in your middleware or in your serviceprovider etc. We can get all our controller details from the current route as like as UserController, HomeController ect. Now we can also get the full path of the controller file.

We can simple get the current controller name in any version of laravel as like as laravel 6, laravel 7 and laravel 8 project.

Laravel getAction() through we can easily get the whole array of the current route details. So in this example i will get the current controller from my auth middleware, if we need on our view file or any other place then we can simply get this on this way.

So, let’s see the example how we can get controller name from the auth middleware.

Example: app/Http/Middleware/Authenticate.php
namespace App\Http\Middleware;


use Closure;
use Illuminate\Support\Facades\Auth;


class Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $routeArray = app('request')->route()->getAction();
        $controllerAction = class_basename($routeArray['controller']);
        list($controller, $action) = explode('@', $controllerAction);
        print_r($controller);
        exit;
        if (Auth::guard($guard)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }
        return $next($request);
    }
}

Read Also: How we can create virtual host in ubuntu apache?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →