Get the name of the current view in Laravel

To fix a problem in a Laravel application I needed access to the name of the current view in the master layout. I found a nice solution for this problem in this post on StackOverflow:

View::composer('*', function($view){
    View::share('view_name', $view->getName());

I added this code to my AppServiceProvider, and I can now use the $view_name variable in all my views. It will contain the name of the view as you called it from your controller, for example pages.home.

One thing to note is that there is a comment to this solution on StackOverflow that says that this works, but that the $view_name will be overwritten if you use @include for partials in your views. In my case this is not an issue, but something to keep in mind if you run into problems.

December 16, 2015

Click Here to Leave a Comment Below

Leave a Reply: