Derp Derp - 1 month ago 6
PHP Question

How to get the route its structure in Laravel

Let's say I have the following route in Laravel:

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});


And let's say I'm on the following url:
posts/3/comments/54


I can get the url as a string by accessing the
url()
method, this would give me back the exact url.

In my case, I need something else. Is there a way to get the route's structure? I want to do something like this:

if(someUrlStructureFunction() == "posts/{post}/comments/{comment}") //do something


Thanks!

Answer

When using resources, the actions have names by default, so your post comments could be:

Route::resource('posts.comments', 'PostsCommentsController');

php artisan route:list
+--------+-----------+----------------------------------------+------------------------+------------------------------------------------------+------------+
| Domain | Method    | URI                                    | Name                   | Action                                               | Middleware |
+--------+-----------+----------------------------------------+------------------------+------------------------------------------------------+------------+
|        | GET|HEAD  | posts/{posts}/comments                 | posts.comments.index   | App\Http\Controllers\PostsCommentsController@index   |            |
|        | POST      | posts/{posts}/comments                 | posts.comments.store   | App\Http\Controllers\PostsCommentsController@store   |            |
|        | GET|HEAD  | posts/{posts}/comments/create          | posts.comments.create  | App\Http\Controllers\PostsCommentsController@create  |            |
|        | GET|HEAD  | posts/{posts}/comments/{comments}      | posts.comments.show    | App\Http\Controllers\PostsCommentsController@show    |            |
|        | PUT|PATCH | posts/{posts}/comments/{comments}      | posts.comments.update  | App\Http\Controllers\PostsCommentsController@update  |            |
|        | DELETE    | posts/{posts}/comments/{comments}      | posts.comments.destroy | App\Http\Controllers\PostsCommentsController@destroy |            |
|        | GET|HEAD  | posts/{posts}/comments/{comments}/edit | posts.comments.edit    | App\Http\Controllers\PostsCommentsController@edit    |            |
+--------+-----------+----------------------------------------+------------------------+------------------------------------------------------+------------+

Then you could use Request::route()->getName() to analyze which one was called.