Skip to content
Advertisement

How to know the controller and method name inside blade file in Laravel 6?

I am new to Laravel. I was practicing setting up a blog in Laravel 6. I have a layout.blade.php file where all the basic HTML is written. In the content section of the layout.blade file, I want to @include other blade file depending on the controller and method name.

I have 2 controllers, HomeController and ArticleController. In HomeController file, there is a method index() which returns the view home.blade.php. Again, home.blade.php @extends layout.blade.php. Now I want to know which controller and method called the view file inside from layout.blade.php file.

I want something like this-

<!-- This is layout.blade.php file -->
<html>
<head>
</head>
<body>
  @if (Controller == HomeController AND Method == index)
    @include('home')
  @endif

  @if (Controller == ArticleController AND Method == index)
    @include('articles')
  @endif
</body>
</html>

I didn’t find any answer on Google. I got some questions in StackOverflow, but they have very confusing answers and those versions are older also.

Thank you.

EDIT 1:

  1. Due to the low reputation score, I cannot reply in comments. As I am new, I know some basic tags of blade, so if there is any other solution to achieve this, please share it with me.
  2. I found Get Laravel 5 controller name in view before making this question. But I don’t think it answers my question.
  3. I know Controller == HomeController AND Method == index is crazy. I just illustrated what I need. I know basic @yield and @section tags, but I don’t want to use this in my case. Because, if I make a card/home section entirely in a different file, I can call it in other files later. If I use @yield, I will have to use @section in different files also, which I don’t want to do.

Advertisement

Answer

Route::currentRouteAction() method seems to be what you want. It’s in the api documentation.

string|null currentRouteAction()

Get the current route action.

Return Value string|null

https://laravel.com/api/6.x/Illuminate/Routing/Router.html#method_currentRouteAction

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement