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!
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.
Give your route a name:
Route::get('user/profile', 'UserController@showProfile')->name('profile');
(That's the Laravel 5.3 syntax. It's slightly different in earlier versions.)
then, you can use:
Request::route()->getName()
to check if you're on that route.
Based on your comment you want to restrict certain routes to specific roles
you can try using route groups then create a middleware for each roles: https://laravel.com/docs/5.3/routing#route-groups
//put your admin routes inside this
Route::group(['middleware' => 'admins'], function () {
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});
});
//put your users routes inside this
Route::group(['middleware' => 'users'], function () {
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});
});