Laravel route group with variable prefix and where condition - laravel

I would like to create a route group in Laravel with a variable as a prefix. I need to set certain conditions too. How to do it properly?
I was following docs: https://laravel.com/docs/8.x/routing#route-group-prefixes but there are only general examples.
This code should create 2 routes: /{hl}/test-1 and /{hl}/test-2 where {hl} is limited to (en|pl), but it gives an error: "Call to a member function where() on null"
Route::prefix('/{hl}')->group(function ($hl) {
Route::get('/test-1', function () {
return 'OK-1';
});
Route::get('/test-2', function () {
return 'OK-2';
});
})->where('hl','(en|pl)');

The group call doesn't return anything so there is nothing to chain onto. If you make the where call before the call to group, similarly to how you are calling prefix, it will build up these attributes then when you call group it will cascade this onto the routes in the group:
Route::prefix('{hl}')->where(['h1' => '(en|pl)'])->group(function () {
Route::get('test-1', function () {
return 'OK-1';
});
Route::get('test-2', function () {
return 'OK-2';
});
});

By analogy with this answer:
Route::group([
'prefix' => '{hl}',
'where' => ['hl' => '(en|pl)']
], function ($hl) {
Route::get('/test-1', function () {
return 'OK-1';
});
Route::get('/test-2', function () {
return 'OK-2';
});
});
Does this solve your problem?

Related

Laravel route group prefix - variable not working

in web.php :
Route::group(['middleware'=>['checklang','checkmoney']],function(){
Route::get('/', function () {
return redirect('/'.session()->get('lang'));
});
Route::group([
'prefix' => '{locale}',
'where'=>['locale'=>'[a-zA-Z]{2}']],
function() {
Route::get('/tour/{id}','HomeController#getTours');
});
});
in HomeContoller :
public function getTours($id){
dd($id);
}
when trying to access url : example.com/en/tour/5
getting result
en , but should be 5
Where is a problem and how to solve it?
Your route has 2 variables, {locale} and {id}, but your Controller method is only referencing one of them. You need to use both:
web.php:
Route::group(['prefix' => '{locale}'], function () {
...
Route::get('/tour/{id}', 'HomeController#getTours');
});
HomeController.php
public function getTours($locale, $id) {
dd($locale, $id); // 'en', 5
}
Note: The order of definition matters; {locale} (en) comes before {id} 5, so make sure you define them in the correct order.

Laravel pass subdomain as a value to another route

now I have this code
Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
Route::any('/', function($subdomain)
{
Route::get('{/subdomain}/{identifier}/{reCreate?}','AController#index');
});
});
I want to pass {subdomain} to Route::get('{/subdomain}/{identifier}/{reCreate?}','AController#index'); for when call subdomain.localhost/identifier I call AController#index I should pass the value of subdomain to AController#index
I think by using Route::input('subdomain'); you can access the subdomain parameter.
Inside AController:
public function index() {
dd(Route::input('subdomain'));
}
Please try this.
Route::domain('{account}.myapp.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
//
});
});
I figured out the answer thanks guys for your help ,
the answer is just call the route inside route::group
Route::group(['domain' => '{subdomain}.'.env('DOMAIN')], function()
{
Route::any('/{identifier}/{reCreate?}','AController#index');
});
and inside Controller function index I can access the value as normal function($subdomain)

Laravel 5 - Named route with parameter

In my web.php file, I created two routes :
Route::get('/{name}', 'PublicController#index')->name('welcome');
Route::get('stats', function () { return route('welcome', 'enrique'); });
My controller looks like:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PublicController extends Controller
{
public function index($name)
{
return view('welcome');
}
}
I already set up a virtual host in my local machine which is http://blog.test
When I Call http://blog.test/stats in my browser, it shows me the content of my homepage. But when I reorganize my twho route in web.php file in that way
Route::get('stats', function () { return route('welcome', 'enrique'); });
Route::get('/{name}', 'PublicController#index')->name('welcome');
It works fine.
Can you please explain why it behaves like that? Thanks
What you have is the same route being overwritten. In order to have them both work, you will have to add something before your custom parameter:
/something/{name}
Otherwise stats is assumed to be value for your parameter name
Laravel route goes to first matched routes, so in your case if it sees /stats
Route::get('/{name}', 'PublicController#index')->name('welcome');
It becomes variable $name for PublicController#index
Check more article regarding this
It is happening because , when you add your {parameter} as after / , all routes defined after that, are considered as of that type
Route::get('/{name}', 'PublicController#index')->name('welcome');
// below routes not work
Route::get('stats', function () {});
Route::get('test', function () { });
Route::get('hello', function () {});
same thing happen if you create new route like below :
Route::get('post/{slug}', function () {});
// this get routes are also not work
Route::get('post/show', function () {});
Route::get('post/preview', function () {});
so it is good practice that always define parameterised route at the
last
Route::get('post/show', function () {});
Route::get('post/preview', function () {});
Route::get('post/{slug}', function () {});

How to get routes list by specific groups in laravel 5?

Hello I am trying to do it like this but it's getting all the routes, I only want the routes from a specific group(s).
This is my code:
<?php
$routes = Routes::getRoutes();
#foreach($routes as $route)
{{ $route->getPath() }}
#endforeach`
Thanks in advance!
Let's create some routes without any groups
Route::get('/', function () {
return view('welcome');
});
Route::get('/load', 'defaultController#load');
Now we'll create some routes with groups
Route::group(['as' => 'admin'], function () {
Route::get('users', function () {
return "users route";
});
Route::get('ravi', function () {
return "ravi route";
});
Now we are going to create a route in this group which will look for the admin group and print all routes that exist in this group.
Route::get('kumar', function () {
$name = 'admin';
$routeCollection = Route::getRoutes(); // RouteCollection object
$routes = $routeCollection->getRoutes(); // array of route objects
Now in our route object, we will look for our named route by filtering the array.
$grouped_routes = array_filter($routes, function($route) use ($name) {
$action = $route->getAction(); // getting route action
if (isset($action['as'])) {
// for the first level groups, $action['as']
// will be a string
// for nested groups, $action['as'] will be an array
if (is_array($action['as'])) {
return in_array($name, $action['as']);
} else {
return $action['as'] == $name;
}
}
return false;
});
// Here we will print the array containing the route objects in the 'admin' group
dd($grouped_routes);
});
});
Now you can copy and paste this in your route folder and you will be able to see the output by hitting your_project_public_folder_url/kumar
I took help from this answer Answer of patricus

Laravel routing groups

I have a question about routing groups. I have two types of users and I can not use the role system. Following the laracast email verification video I was able to get a new type of user to work. So I can login and register no problem. However when I have both types of users routes going it starts rejecting logins and such.
I even tried separating the admin user routes and putting the artist user routes on a different php document but still will not allow two types of logins or to view the proper dashboard.
I have tried using namespace inside the group, prefix, and tried middleware to no avail.
Here's the routing code.
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('welcome');
});
Route::get('/artist', function () {
return view('artist');
});
Route::get('/sponsor', function () {
return view('sponsor');
});
Route::get('/viewer', function () {
return view('viewer');
});
Route::get('/contact', function () {
return view('contact');
});
// This is for the Artist Linkings
//Route::group(['middleware' => 'artist'], function () {
//Route::auth('artist');
//Route::get('art/dashboard', 'SessionsController#index');
//Route::get('art/dashboard', ['middleware' => 'artist', function() {
//return view('art/dashboard');
//}]);
//});
//Route::get('art/register', 'RegistrationController#register');
//Route::post('art/register', 'RegistrationController#postRegister');
//Route::get('register/confirm/{token}', 'RegistrationController#confirmEmail');
//Route::get('art/login', 'SessionsController#login');
//Route::post('login', 'SessionsController#postLogin');
//Route::get('/logout', 'SessionsController#logout');
//Route::get('art/dashboard', 'SessionsController#index');
//});
// Need to add the password stuff ect
// Route::group(['prefix' => 'viewer', 'namespace' => 'Viewer'], function () {
// require app_path('Http/Routes/viewers.php');
// });
// This is for all the Viewer Linkings
Route::get('viewer/register', 'ViewerRegistrationController#register');
Route::post('viewer/register', 'ViewerRegistrationController#postRegister');
Route::get('viewer/register/confirm/{token}', 'ViewerRegistrationController#confirmEmail');
Route::get('viewer/login', 'ViewerSessionsController#login');
Route::post('login', 'ViewerSessionsController#postLogin');
Route::get('/logout', 'ViewerSessionsController#logout');
Route::get('viewer/dashboard', 'ViewerSessionsController#index');
//});
//}]);
You can use this .
For artist user as you define
Route::group(["middleware" => ["auth.artist"], "prefix" => "artist","namespace"=>"Artist"], function() {
Route::controller('artist', 'UsersArtistController');
Route::controller('controles', 'controlsArtistController');
});
For viewer user if no any auth needed
Route::group("prefix" => "viewer","namespace"=>"Viewer"], function() {
Route::controller('Viewer ', 'UsersViewer Controller');
Route::controller('controles', 'controlsViewerController');
});
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
Route::resource('tag','TagController');
Route::resource('category','CategoryController');
});
Route::group(['middleware'=>['auth']], function(){
Route::post('favorite/{post}/add','FavoriteController#add')->name('post.favorite');
Route::post('review/{id}/add','ReviewController#review')->name('review');
});
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
Route::resource('post','PostController');
});

Resources