Laravel Detect Route Group in View - php

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.

Related

Laravel Language changer

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']) ) }}

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 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 form post issue

I am building a practice app with the Laravel framework I built a form in one of the views which is set to post to the same view itself but when I hit submit the form is posted however I do not get the desired output, I see the original view again.
Here is my view index.blade.php
#extends('master')
#section('container')
<div class="wrapper">
{{ Form::open(array('url' => '/', 'method' => 'post')) }}
{{ Form::text('url') }}
{{ Form::text('valid') }}
{{ Form::submit('shorten') }}
{{ Form::close() }}
</div><!-- /wrapper -->
#stop
and my routes.php
Route::get('/', function()
{
return View::make('index');
});
Route::post('/', function()
{
return 'successfull';
});
What I've tried so far
I tried changing the post to a different view and it worked.
However I want the form to post to the same view itself.
Instead of returning a string I tried to return make a view still it
didn't work.
What am I doing wrong?
addendum
I see that when the form is making the post request I am getting a 301 MOVED PERMANENTLY HEADER
{{ Form::open(array('url' => ' ', 'method' => 'post')) }}
Passing a space as the url has worked for me.
I think this post: Form submits as GET Laravel 4 is related to your problem. I think the problem as I undersood it is caused by end a form url with a / . I found this when having problems to using post to a ./ url in my form. There is also a bug at github that seems like it is related https://github.com/laravel/framework/issues/1804.
I know this is an old question but I found this thread having the same problem so hopefully someone else is helped by my answer.
You need to make sure that your form's method does NOT end in a / for it to be routed correctly. For example if you have the following route:
Route::post('form/process', function()
{
# code here ...
});
Then you need to have the following form definition:
<form action="/form/process" method="POST">
I hope that helps.
I have same problem with OSx + MAMP, initially I've resolved with Raul's solution:
{{ Form::open(array('url' => ' ', 'method' => 'post')) }}
but after consultation with my friend we have concluded that my problem was due to the fact
my lavarel project is avaliable by long local path, as:
http://localhost/custom/custom2/...
in this location the post/get method on root path ("/") not working correctly.
Lavarel to working correctly must be avaliable by "vhost", in this case the problem get/post method on root location "/" not exist.
My friend advised me to use http://www.vagrantup.com/
BYE
There is some helpfull information in the Laravel Docs. Check these out:
Resource Controllers (or RESTful Controllers)
Forms & HTML
Opening A Form
Routing
Named Routes
I recommend you read the Resource Controllers documentation as it makes form handling a lot easier.
Well, you just return the view, so nothing change. You should bind your route to a controller to do some logic and add data to your view, like this:
index.blade.php
#extends('master')
#section('container')
<div class="wrapper">
#if (isset($message))
<p>{{$message}}</p>
#endif
{{ Form::open(array('url' => '/', 'method' => 'post')) }}
{{ Form::text('url') }}
{{ Form::text('valid') }}
{{ Form::submit('shorten') }}
{{ Form::close() }}
</div><!-- /wrapper -->
#stop
Your routes
Routes::any('/', 'home#index');
You controller HomeController.php
public function index()
{
$data = array();
$url = Input::get('url');
if ($url)
$data['message'] = "foo";
return View::make('index', $data);
}
You can also modify your current routes without using a controller like this (use the new view file)
Route::get('/', function()
{
return View::make('index');
});
Route::post('/', function()
{
return View::make('index')->with('message', 'Foo');
});
The problem is with defualt slashed in Apache from 2.0.51 and heigher:
http://httpd.apache.org/docs/2.2/mod/mod_dir.html#directoryslash
The best solution if you do not want to change Apache config is to make the post in a different path:
GOOD:
Route::get('/',
['as' => 'wizard', 'uses' => 'WizardController#create']);
Route::post('wizard-post',
['as' => 'wizard_store', 'uses' => 'WizardController#store']);
NOT GOOD:
Route::get('/',
['as' => 'wizard', 'uses' => 'WizardController#create']);
Route::post('/',
['as' => 'wizard_store', 'uses' => 'WizardController#store']);

Categories