How to get current Controller and current Action name in Laravel

Laravel

Posted on 26 Jan 16 by Vickey
  3019



Some times in our projects we need to get current controller or current action name in our code or controller. We can do this in Laravel also by the help of Routing. First of all you need to add the below code at the top in your controller file

use Illuminate\Routing\Route;

Now add this code in your controller class

public $cointrollerName='';
public $actionName='';
public function __construct(Route $route)
{
	$currentAction= $route­>getActionName();
	list($controller, $method) = explode('@', $currentAction);
	$this­>cointrollerName= preg_replace('/.*\\\/', '', $controller);
	$this­>actionName=preg_replace('/.*\\\/', '', $method);
}

and now you can get your controller or action name by using code

	echo $this­>cointrollerName;

	echo $this­>actionName

The complete code will look like this

use Illuminate\Routing\Route;
class ApiController extends Controller
{
	public $cointrollerName='';
	public $actionName='';

	public function __construct(Route $route)
	{
		$currentAction= $route­>getActionName();
		list($controller, $method) = explode('@', $currentAction);
		$this­>cointrollerName= preg_replace('/.*\\\/', '', $controller);
		$this­>actionName=preg_replace('/.*\\\/', '', $method);
	}

	public function index(){

		echo $this­>cointrollerName;
		echo $this­>actionName 
	}

}

 


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com