get Route name in View - php

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.

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 how to get current Route

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

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'.

laravel 4-call_user_func_array()

I am trying to insert some data in database. I have created form with all fields and controller.
CarController.php
public function create() {
// load the create form (app/views/pages/create.blade.php)
return View::make('pages.create');
}
public function store() {
// store
$data = new Car;
$data->id = Input::get('id');
$data->save();
// redirect
Session::flash('message', 'Successfully created data!');
return Redirect::to('pages/cars');
}
routes.php
Route::resource('cars', 'CarController');
Route::post('desc', array('uses' => 'CarController#show'));
Route::post('create', array('uses' => 'CarController#create'));
Route::post('store', array('store' => 'CarController#store'));
create.blade.php
{{ Form::open(array('url' => 'store', 'class'=>'form-horizontal')) }}
<div class="form-group">
{{ Form::label('id', 'Vehicle ID',array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::text('id', Input::old('textId'), array('class' => 'form-control', 'placeholder'=>'Vehicle ID')) }}
</div>
</div>
{{ Form::submit('Create the Car!', array('class' => 'btn btn-primary')) }}
</div>
The problem is that it shows the following error:
expects parameter 1 to be a valid callback, no array or string given
I dont know what I have done wrong because I am new at laravel
You are using a resource controller and that's why you only need one route declaretion for this, like:
Route::resource('cars', 'CarController');
You have also declared following routes:
Route::post('desc', array('uses' => 'CarController#show'));
Route::post('create', array('uses' => 'CarController#create'));
Route::post('store', array('store' => 'CarController#store'));
Actually you don't need these route declarations, only use first route and this will create routes for your resource controller. For example, your routes would look like these:
Method | Url | Action | Route Name
--------------------------------------------
GET | /cars/create | create | cars.create // domain.com/cars/create using GET
POST | /cars | store | cars.store // domain.com/cars using POST
There are more, you should check the Resource Controllers. In this case, you have two methods in your controller and if you use a url like yourdomain.com/cars/create using GET method (if you navigate from browser's address bar) then it'll invoke create method and if you submit a form using POST method to yourdomain.com/cars then it'll invoke the store method and all your form fields will be available in the $_POST array and you can use Input::get('id') to get id field's value. Check the socumentation for more information.
change this line in the route.php file
Route::post('store', array('store' => 'CarController#store'));
to
Route::post('uses', array('uses' => 'CarController#store'));
'uses' specify which function to call when you access the route

Categories