ItSolutionStuff.com

How to Get Current Controller Name in View Laravel?

By Hardik Savani • April 16, 2024
Laravel

If you require to get current controller name in your view file or in your middleware or your serviceprovider etc. you can get your controller details from current route like UserController, HomeController ect. you can also get full path of controller file.

you can simple get current controller name in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 project.

Laravel getAction() through we can get whole array of current route details, in this example i get current controller in my auth middleware, if you require on your view file or other place then you can simply get.

So, let's see example how you can get controller name in 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);

}

}

Tags: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Get Current Full URL in Laravel 10?

Read Now →

Laravel 10 Get Current Logged in User Data Example

Read Now →

Laravel Migration Default Value Current Timestamp Example

Read Now →

How to Pass Data from Controller to View in Laravel?

Read Now →

Laravel Route Pass Multiple Parameters Example

Read Now →

How to Get All Routes in Laravel?

Read Now →

How to use Carbon in Laravel Blade or Controller File?

Read Now →

How to Call Controller Function in Blade Laravel?

Read Now →

Laravel Redirect to Route from Controller Example

Read Now →

Laravel 9 Get Current User Location From IP Address

Read Now →

How to Get All Session Data in Laravel?

Read Now →

How to Get Current URL in Laravel?

Read Now →

How to Get Current Route Name in Laravel?

Read Now →

How to Get Last Inserted Id in Laravel?

Read Now →