How to config Laravel Router some route rule work on different path? - laravel

I deployed my Laravel 5 project on A.com, I also want put it under B.com/a. For some reason, the /a path I should handle it in router.
So in router I write:
Route::get('post','PostController#index');
Route::get('a/post','PostController#index');
It's not a good way because there is redundancy, especially there are a lot of other route rules.
In the doc, there is only {xx}? to handle optional param, but in my project, it's not param instead of a static string.
It's there any better way to combine two lines?

I'd use a route prefix within a foreach loop. That'd allow you to quickly and easily manage the prefixes on your routes while keeping them all in one place.
foreach([null, 'a'] as $prefix) {
Route::group(['prefix' => $prefix], function () {
// Your routes here
});
}
The routes not prefixed will take precedence as their routes would be generated first in this case. You could just as easily swap the array around if necessary.
If you really wanted to do it in a single route definition you could do it using a regular expression to match the route.
Route::get('{route}', function () {
dd('Browsing ' . app('request')->path());
})->where('route', '(a/)?post');
But it's clearly not very clean/readable so probably not recommended.

You can do this:
RealRoutes.php:
Route::get('post','PostController#index');
// ... include all of your other routes here
routes.php:
include('RealRoutes.php');
Route::group(['prefix' => 'a/'], function () {
include('RealRoutes.php');
});
There's probably a better way to solve this using a lambda function or similar but the above should work as a quick solution.

Related

Add username as prefix in route URI in Laravel 9

I am building an application where users are registered and want to be redirected to their individual dashboard like this .
http://localhost/project/{username}/dashboard,
Now, its happening like
localhost/project/vendors/dashboard (here all users are accessing same URL)
but I want to make it like :
http://localhost/project/{username1}/dashboard, http://localhost/project/{username2}/dashboard
Googled lot but none of them are explained well and working.
Please assist with complete flow.
I want to declare the value of {username} globally and use it in route as prefix.
I dont want to use it before each name route. will use it as prefix and group with all vendors routes
I have made this, and its working as
localhost/project/vendors/dashboard
Route::prefix('vendors')->group(function () { Route::middleware(['auth:vendor'])->group(function () { Route::get('/dashboard', [VendorController::class, 'dashboard'])->name('vendor.dashboard'); });
});
You can specify route parameters in brackets like so {parameter}, change your code into this.
Route::get('project/{username}/dashboard', [UserDashboardController::class, 'dashboard'])
->name('user.dashboard');
In your controller you could access it like this.
class UserDashboardController
{
public function dashboard(string $username)
{
User::where('username', $username)->firstOrFail();
// something else
}
}
Seems like in your routes your are mixing vendor prefix logic in with something that in your specifications of what your urls should look like does not match. Which i think is making up some of the confusion on this case.
You can use route prefix like this
Route::prefix('{username}')->group(function () {
Route::middleware(['auth'])->group(function () {
Route::get('/dashboard', [UserController::class, 'dashboard'])->name('user.dashboard');
});
});

Laravel route service provider not triggered for domain key

I’m creating a SaaS app (who isn’t?) and like most SaaS apps, I’ve taking the account subdomain approach. My routes file looks like this:
$router->group(['domain' => '{account}.example.com'], function($router)
{
$router->get('/', function()
{
return response('Hello, world.');
});
});
I then decided to add some route parameter validation and binding in my RouteServiceProvider file:
public function boot(Router $router)
{
parent::boot($router);
$router->pattern('account', '[a-z0-9]+');
$router->bind('account', function($subdomain)
{
return Account::whereSubdomain($subdomain)->firstOrFail();
});
}
However, these don’t actually seem to be triggered. I know this as I can put something like dd('here?') in the bind call, and it’s never triggered. I can also reduce my account pattern filter to something like [0-9]+ and it’ll still be matched if I include letters in the subdomain.
What am I doing wrong? How can I get route patterns and bindings to work on variables in the domain key of my route group?
Turns out moving any bindings to the map method (instead of the boot) method works, and pattern filters need to go inside the route group definition, like so:
$router->group(['domain' => '{account}.example.com'], function($router)
{
$router->pattern('account', '[a-z0-9]+');
$router->get('/', function()
{
return response('Hello, world.');
});
});
Not ideal, so any one knows how to have filter patterns be kept in my RouteServiceProvider class so they’re not littered in my routes file, then would love to hear from you.

Laravel passing all routes for a particular domain to a controller

Working on a Laravel 4.2 project. What I am trying to accomplish is pass every URI pattern to a controller that I can then go to the database and see if I need to redirect this URL (I know I can do this simple in PHP and do not need to go through Laravel, but just trying to use this as a learning experience.)
So what I have at the moment is this:
Route::group(array('domain' => 'sub.domain.com'), function()
{
Route::get('?', 'RedirectController#index');
});
I am routing any subdomain which I deem as a "redirect subdomain" ... The ? is where I am having the problem. From what I have read you should be able to use "*" for anything but that does not seem to be working. Anyone have a clue how to pass any URL to a controller?
And on top of that I would ideally like to pass the FULL URL so i can easily just check the DB and redirect so:
$url = URL::full();
Try this:
Route::group(array('domain' => 'sub.domain.com'), function()
{
Route::get('{path}', 'RedirectController#index')
->where('path', '.*');
});
And your controller will reseive the path as first argument
public function index($path){
// ...
}
In case you're wondering, the where is needed because without it {path} will only match the path until the first /. This way all characters, even /, are allowed as route parameter

Laravel routing & filters

I want to build fancy url in my site with these url patterns:
http://domain.com/specialization/eye
http://domain.com/clinic-dr-house
http://domain.com/faq
The first url has a simple route pattern:
Route::get('/specialization/{slug}', 'FrontController#specialization');
The second and the third url refers to two different controller actions:
SiteController#clinic
SiteController#page
I try with this filter:
Route::filter('/{slug}',function()
{
if(Clinic::where('slug',$slug)->count() == 1)
Route::get('/{slug}','FrontController#clinic');
if(Page::where('slug',$slug)->count() == 1)
Route::get('/{slug}','FrontController#page');
});
And I have an Exception... there is a less painful method?
To declare a filter you should use a filter a static name, for example:
Route::filter('filtername',function()
{
// ...
});
Then you may use this filter in your routes like this way:
Route::get('/specialization/{slug}', array('before' => 'filtername', 'uses' => 'FrontController#specialization'));
So, whenever you use http://domain.com/specialization/eye the filter attached to this route will be executed before the route is dispatched. Read more on documentation.
Update: For second and third routes you may check the route parameter in thew filter and do different things depending on the parameter. Also, you may use one method for both urls, technically both urls are identical to one route so use one route and depending on the param, do different things, for example you have following urls:
http://domain.com/clinic-dr-house
http://domain.com/faq
Use a single route for both url, for example, use:
Route::get('/{param}', 'FrontController#common');
Create common method in your FrontController like this:
public function common($param)
{
// Check the param, if param is clinic-dr-house
// the do something or do something else for faq
// or you may use redirect as well
}

How to set multiple patterns for Laravel 4 route?

I had this piece of route in a project in Laravel 3:
Route::get(array('/Home', '/'.rawurlencode ('خانه')), function()
{
return View::make('home.index');
});
It was working correctly, till I decided to migrate it to Laravel 4. Now in Laravel 4 I get this error:
preg_match_all() expects parameter 2 to be string, array given
Are there any other way to set multiple patterns for Laravel 4 route?
You can achieve this using where with your route,
So if your route is,
Route::get('{home}', function()
{
return View::make('home.index');
})->where('خانه', '(home)?');
You can access the same using,
http://localhost/laravel/home
http://localhost/laravel/خانه
Here the http://localhost/laravel/ should be replaced with yours.
Using regex is the best way,
Route::get('{home}', function()
{
return View::make('home.index');
})->where('home', '(home|خانه)');
This will match only,
http://localhost/laravel/home
http://localhost/laravel/خانه
You can use regex in the route so maybe something like this.
Route::get('(Home|' . rawurlencode('خانه') . ')', function ()
{
return View::make('home.index');
});
If that doesn't work I'd probably just define two route's because the closure is so simple. Even if it is more complex, you could move it to a controller and point two routes at the same controller method.

Resources