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');
});
Related
i want to add a function to my resource controller. i've read some articles that said we have to put the route line before the resource line and that is what i did. but i still get and error that says route not defined.
Route::name('panel.')->prefix('panel')->middleware('auth')->group(function () {
Route::get('/dashboard', [DashboardController::class, 'index'])->name("dashboard");
Route::resource('contact', ContactController::class)->only([
'index', 'show', 'destroy'
]);
Route::post('/portfolio' , [PortfolioController::class, 'visibility']);
Route::resource('portfolio', PortfolioController::class)->except([
'show'
]);
Route::resource('customer', CustomerController::class)->except([
'show'
]);
Route::resource('advice', AdviceController::class)->only([
'index', 'destroy'
]);
Route::resource('invoice', InvoiceController::class)->only([
'index', 'destroy', 'create', 'store',
]);
Route::resource('email', EmailTemplateController::class)->only([
'index', 'destroy', 'create', 'store',
]);
Route::resource('profile', ProfileController::class)->only([
'update', 'index', 'destroy'
/*
* index
* destroy
*/
]);
Route::get('/me', [ProfileController::class, 'show'])->name("profile.show");
});
this is my web.php
the name of the route should be panel.portfolio.visibility.
also another thing i did not write the code to this project im just adding a few features to it. so the new function is mine but not the resource controller.
public function visibility(Request $request,$portfolio_id)
{
$portfolio= Portfolio::find($portfolio_id);
if($portfolio instanceof Portfolio){
$this->validate($request,[],[]);
$indicator = ($request->input('custom-switch-checkbox') == 'on') ? 1 : 0;
$newData= ['portfolio_visibility' => $indicator];
$portfolio->update($newData);
return redirect()->back()->with('success', 'با موفقیت به روز رسانی گردید.');
}
}
this is my visibility function.
there is this page that shows the list of the portfolios and there is a column where theres a switch that indicates if the portfolio should be shown or not.
i can create portfolios just fine but i cant enter the list page which is the index page here.
<td>
<!--dokme baraye namayesh -->
<form action="{{ route('panel.portfolio.visibility' , $portfolio->portfolio_id ) }}" role="form" method="post">
<label class="custom-switch mt-2" >
<input type="checkbox" name="custom-switch-checkbox"
class="custom-switch-input"
id="personal-data-button" {{($portfolio->portfolio_visibility== 0)? '': 'checked'}} onclick="{{ route("panel.portfolio.visibility" , $portfolio->portfolio_id ) }}">
<span class="custom-switch-indicator"></span>
</label>
</form>
</td>
this is in the index.blade.php
i dont know why theres a problem.
also i am fairly new to laravel so if my question is confusing or sounds stupid please be kind.
When you use Route::resource it does it for you with default naming convention. If you use Route::post you have to specify the name like it is done in your dashboard route.
So changing your route this way should work:
Route::post('/portfolio' , [PortfolioController::class, 'visibility'])->name('portfolio.visibility');
Docs: https://laravel.com/docs/8.x/routing#named-routes
as for me there were codes I comment out which the error occurs. I deleted those and all turns fine.
I add localization to my laravel app. I define language in my routes.
Route::group(['prefix' => '{language}/tender', 'middleware' => ['permission:tender-page']], function () {
Route::get('/', 'TenderController#index')->name('tender');
Route::get('/add', 'TenderController#add')->name('tender_add');
Route::get('/{id}', 'TenderController#detail')->name('tender_detail');
});
I try to change languages by this way
<li class="nav-item">
RU
</li>
<li class="nav-item">
TR
</li>
but if i use this way, this kind of routes Route::get('/{id}', 'TenderController#detail')->name('tender_detail'); got error.
How can realize language changer?
You need to pass the {id} parameter again.
{{ route(Route::currentRouteName(), ['language' => 'ru', 'id' => $tender_id]) }}
You need to get your current route parameters and override the {language}. You can accomplish this by getting the current route's parameter array with Route::current()->parameters() and then using array_merge to override the language.
{{ route(Route::currentRouteName(), array_merge(Route::current()->parameters(), ['language' => 'ru']) ) }}
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
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.
I trying to design navigation menu,
I have 3 Items like this:
Dashboard
Pages
List
Add
Articles
List
Add
Now I want to bold Pages when user is in this section,
and if is in Add page I want bold both Pages and Add
my routes.php is :
Route::group(array('prefix' => 'admin', 'before' => 'auth.admin'), function()
{
Route::any('/', 'App\Controllers\Admin\PagesController#index');
Route::resource('articles', 'App\Controllers\Admin\ArticlesController');
Route::resource('pages', 'App\Controllers\Admin\PagesController');
});
I found thid method :
$name = \Route::currentRouteName();
var_dump($name);
But this method return string 'admin.pages.index' (length=17)
Should I use splite to get controller or Laravel have a method for this ?
In Blade:
<p style="font-weight:{{ (Route::current()->getName() == 'admin.pages.index' && Request::segment(0) == 'add') ? 'bold' : 'normal' }};">Pages</p>
Request::segments() will return an array with the current url for example:
yoursite/admin/users/create
will give:
array(2) {
[0] "admin"
[1] "users"
[2] "create"
}
You may use this (to get current action, i.e. HomeController#index)
Route::currentRouteAction();
This will return action like HomeController#index and you can use something like this in your view
<!-- echo the controller name as 'HomeController' -->
{{ dd(substr(Route::currentRouteAction(), 0, (strpos(Route::currentRouteAction(), '#') -1) )) }}
<!-- echo the method name as 'index' -->
{{ dd(substr(Route::currentRouteAction(), (strpos(Route::currentRouteAction(), '#') + 1) )) }}
The Route::currentRouteName() method returns the name of your route that is used as 'as' => 'routename' in your route declaration.