Laravel how to get current Route - php

I have the following in my Routes.php:
Route::get('cat/{cat}', ['as' => 'cat', 'uses' => 'CatController#get']);
I want to check in my sidebar.blade.php file if any of the views returned from the Controller function matches the current page.
{cat} could be either a,b,c,d,f or e.
The sidebar consists of 6 images.
If for example the route is cat/a the image of tis route should be changed.
People suggested Route::current()->getName() but this only returns cat and not /a, /b, /c, etc. Also some other functions are only returning cat/ and nothing after that

You can use Request::is('cat/a').

You can get {cat} part with this:
$cat = Request::route()->getParameter('cat');
And the route with:
$route = Route::currentRouteName();

In your routes/web.php:
Route::get('cat/{cat}', ['as' => 'cat', 'uses' => 'CatController#get'])->name('name-your-route');
In view.blade.php:
#if(request()->routeIS('name-your-route'))
#endif

Related

How to define route group name in laravel

Is there any way to define the name of route group in laravel?
What I'm trying to accomplish by this is to know that the current request belongs to which group so I can make active the main menu and sub menu by the current route action:
Code:
Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
Route::get('/', 'AccountController#index')->name('index');
Route::get('connect', 'AccountController#connect')->name('connect');
});
Route::group(['prefix'=>'quotes','as'=>'quote.'], function(){
Route::get('/', 'QuoteController#index')->name('index');
Route::get('connect', 'QuoteController#create')->name('create');
});
Navigation HTML Code
<ul>
<li> // Add class 'active' when any route is open from account route group
Accounts
<ul>
<li> // Add class 'active' when connect sub menu is clicked
Connect Account
</li>
</ul>
</li>
<li> // Add class 'active' when any route is open from quote route group
Quotes
<ul>
<li> // Add class 'active' when create sub menu is clicked
Create Quote
</li>
</ul>
</li>
</ul>
Now what I want is to call a function or something which will give me the current route's group name.
Examples:
If I'm on index or create page of quotes getCurrentRouteGroup() should return quote
If I'm on index or connect page of accounts getCurrentRouteGroup() should return account
This should work:
Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
Route::get('/', ['as' => 'index', 'uses' => 'AccountController#index']);
Route::get('connect', ['as' => 'connect', 'uses' = > 'AccountController#connect']);
});
Look here for an explanation and in the official documentation (under Route Groups & Named Routes).
Update
{{ $routeName = \Request::route()->getName() }}
#if(strpos($routeName, 'account.') === 0)
// do something
#endif
Alternative from Rohit Khatri
function getCurrentRouteGroup() {
$routeName = Illuminate\Support\Facades\Route::current()->getName();
return explode('.',$routeName)[0];
}
You can use Route::name()->group(...) to prefix all names for a group of routes
Route::name('foo.')->prefix('xyz')->group(function() {
Route::get('path', 'SomeController#method')->name('bar');
});
Here route('foo.bar') resolves to url /xyz/path
See related Laravel Docs
Don't forget to append dot in the prefix name :-)
// both the format of defining the prefix are working,tested on laravel 5.6
Route::group(['prefix'=>'accounts','as'=>'account.'], function() {
Route::get('/', 'SomeController#index')->name('test');
Route::get('/new', function(){
return redirect()->route('account.test');
});
});
Route::group(['prefix' => 'admin', 'as' => 'admin.'], function () {
Route::get('/', [
'as' => 'custom',
'uses' => 'SomeController#index'
]);
Route::get('/custom', function(){
return route('admin.custom');
});
});
laravel 9 documentation says:
The name method may be used to prefix each route name in the group with a given string. For example, you may want to prefix all of the grouped route's names with admin. The given string is prefixed to the route name exactly as it is specified, so we will be sure to provide the trailing . character in the prefix:
Route::name('admin.')->group(function () {
Route::get('users', function () {
// Route assigned name "admin.users"...
})->name('users');
});
Try this
Route::group(['prefix'=>'accounts','as'=>'account.'], function(){
Route::get('connect', [
'as' => 'connect', 'uses' => 'AccountController#connect'
]);
});
It should work-
inside blade-
{{ $yourRouteName = \Request::route()->getName() }}
// Find the first occurrence of account in URL-
#if(strpos($routeName, 'account.') === 0)
console the message or your code
#endif
In Laravel 9 you can now do this:
Route::controller(AccountController::class)->group(function () {
Route::get('/', 'index')->name('index');
Route::get('/connect', 'connect')->name('connect');
});

Laravel 5 - link_to_route() method making my route parameters to change into Query String by adding "?" at the end

After hours of searching I still could not find my answer regarding L5.
What my issue is :
I want to make a link something like this:
localhost:800/songs/you-drive-me-crazy
BUT what is get is:
localhost:800/songs?you-drive-me-crazy
my route parameter is changing into query string.
//routes.php
$router->bind('songs', function($slug)
{
return App\Song::where('slug', $slug)->first();
});
$router->get('songs', ['as' => 'songs.index', 'uses' => 'SongsController#index'] );
$router->get('songs/{songs}', ['as' => 'songs.show', 'uses' => 'SongsController#show'] );
I am using:
{!! link_to_route('songs.index', $song->title, [$song->slug]) !!}
I have tried everything but not succeeded yet,your suggestion may be helpful.
Thanks.
Your usage of link_to_route is incorrect:
{!! link_to_route('songs.index', [$song->title, $song->slug]) !!}
The first parameter is the route name, the second parameter is an array of route parameters, preferably using key value. Because you did not show your defined route, it's hard to guess what this associative array should look like:
{!! link_to_route('songs.index', ['title'=>$song->title, 'slug'=>$song->slug]) !!}
Also I advise you to use the documented functions: route(), see: http://laravel.com/docs/5.0/helpers#urls
A correctly requested route using route():
{!! route('songs.index', ['title'=>$song->title, 'slug'=>$song->slug]) !!}
A properly formatted route would then be:
Route::get('songs/{title}/{slug}', ['as' => 'songs.index', 'uses' => 'SomeController#index']);
This will result in a URL like: http://localhost:800/songs/you-drive-me-crazy/slug
If you only want to add the title to the URL but not the slug, use a route like this:
Route::get('songs/{title}', ['as' => 'songs.index', 'uses' => 'SomeController#index']);
This will result in a URL like: http://localhost:800/songs/you-drive-me-crazy/?slug=slug
Using
Route::get('songs/{slug}', ['as' => 'songs.index', 'uses' => 'SomeController#index']);
The URL will be like: http://localhost:800/songs/you-drive-me-crazy/?title=title assuming the slug now is you-drive-me-crazy
Any added parameter in a route() call will be added as a GET parameter if it's not existing in the route definition.
fixed it, thanks for your great concerns and suggestions.
I was linking to wrong route here:
`{!! link_to_route('songs.index', $song->title, [$song->slug]) !!}`
now, I changed it as :
`{!! link_to_route('songs.show', $song->title, [$song->slug]) !!}`
and it did the trick.

Laravel Detect Route Group in View

In my admin pages, I want to manage my ecommerce products using AngularJS.
e.g. admin/product which will query an api in admin/api/product
I have not yet set up user authentication so I dont yet know if the user is an admin user or not.
I only wish to include angularjs admin scripts on admin pages.
Is there a way I can include an angular adminapp.js in my view only if the route group is admin. e.g. for public facing pages, I don't expose the adminapp.js to public facing pages.
I know I can do this if the user is authenticated as admin - but I wish to be able to do this if the route group is admin.
Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
Route::group(['prefix' => 'api', 'namespace' => 'Api'], function() {
Route::resource('product', 'ProductController');
});
Route::group(['namespace' => 'Product'], function() {
Route::get('product', 'ProductController');
});
});
And in the templates.master.blade.php something like:
#if($routeGroupIsAdmin)
{{ HTML::script('js/adminapp.js') }}
#endif
or even:
{{ Route::getCurrentRoute()->getPrefix() == 'admin'? HTML::script('js/adminapp.js') : HTML::script('js/app.js') }}
But the problem with above example is that if I am in a deep nested view: admin/categories/products then my prefix will no longer be admin. I don't want to go down the route of using a regex to detect the word admin in the route prefix.
There's no built in way that I know of, but here's something that works:
First, add a route filter
Route::filter('set-route-group', function($route, $request, $value){
View::share('routeGroup', $value);
});
Then add this to your admin group (you can also use it for other groups in the future):
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'before' => 'set-route-group:admin'], function(){
Also add this at the top of the routes file to make sure the $routeGroup variable is always set:
View::share('routeGroup', null);
Then in your view:
#if($routeGroup == 'admin')
{{ HTML::script('js/adminapp.js') }}
#endif
You can use the route segments.
if your group prefix is 'admin' and the URL looks like this http://example.com/admin/home,
You can just check it on the blade using Request::segment(1). it renders the first segment of the URL.
#if(Request::segment(1) == 'admin')
{{HTML::script('js/adminapp.js')}}
#endif
If you are checking another segment just change the index.

Laravel route not defined

I'm trying to send a contact form with Laravel
So in the top of my contact form I have this
{{ Form::open(['action' => 'contact', 'name'=>"sentMessage", 'id'=>"contactForm"])}}
I have routes for contact page like this
Route::get('/contact', 'PagesController#contact');
Route::post('/contact','EmailController#test');
in my EmailController file I have something like this
public function test()
{
return View::make('thanks-for-contact');
}
Whenever I open my contact page I get this error message
Route [contact] not defined
when you use the attribute action you provide it a method in your controller like so :
// an example from Laravel's manual
Form::open(array('action' => 'Controller#method'))
maybe a better solution with be to use named routes, which will save you a lot of time if you ever wanted to change your URL.
Route::get('/contact', array('as' => 'contact.index', 'uses' => 'PagesController#contact'));
Route::post('/contact', array('as' => 'contact.send', 'uses' => 'EmailController#test'));
then your form will look something like this :
{{ Form::open(array('route' => 'contact.send', 'name'=>"sentMessage", 'id'=>"contactForm")) }}
You are using 'action' in your opening tags, so its trying to go to a controller by that name. Try using 'url' => 'contact'.

Route not found exception in Laravel Blade View - Route [user.update] not defined

I have defined route in Route File as :
Route::get('user/update','Users#Update');
I want to fill my model data to form so i am writing form::model
<?php echo Form::model($users,array('route' => array('user.update', $users->id))) ?>
It show me error :
Route [user.update] not defined.
If i write
<?php echo Form::model($users) ?>
Then it is working perfectly.
The default method created by the Form class is "POST", so you need:
1) to name the route (as correctly pointed out by #Joel);
2) to make it answer to the proper HTTP verb:
Route::post('user/{id}/update',['as' => 'user.update', 'uses' => 'Users#Update']);
If you're using it for both GET and POST, use the any method:
Route::any('user/{id}/update',['as' => 'user.update', 'uses' => 'Users#Update']);

Categories