how is it possible to dynamic route - laravel

I want to get a dynamic route function into Laravel 6.x
Route::get('/', 'HomeController#index')->name('home');
Route::get('/{code}', 'DetailController#detail1')->name('detail1');
Route::get('/impress', 'ImpressController#index')->name('impress');
If the URL contains a code with 4 digits, DetailController#detail1 should be called.
If the URL contains a code with 8 or 9 digits, DetailController#detail2 should be called.
However, it should still be possible, for example, to call the imprint controller.
How can this be realized?
Thanks for help.

You should use regex to define the constraint on your parameter:
Route::get('/{code89}', 'DetailController#detail1')->where('code89', '[0-9]{8,9}')->name('detail2');
Route::get('/{code4}', 'DetailController#detail1')->where('code4', '[0-9]{4}')->name('detail1');
See : https://laravel.com/docs/6.x/routing#parameters-regular-expression-constraints
Define them in this order or detail1 will always be matched and never detail2.

Related

Routes laravel 9

I'm trying to insert the route according to the positus whatsapp api documentation in laravel 9, however, an error occurs in the route, could someone help me?
enter image description here
You cannot use positional argument after named arguments.
So you should use named arguments for every argument, or none at all.
Route::post('uri', 'action');
// OR
Route::post(uri: 'uri', action: 'action');
Should not be:
Route::post(uri: 'webhook',....
Should instead be:
Route::post('webhook', function(...

Laravel 5 - Define custom route method?

I just got an issue , i have 2 problems :
I want create a custom route for fast using without copy past code many time. Example Laravel 5 have default Route:resource (...) to make Restful! But i want to make my custom route function , Route:api(...) , Route:xxx(...) ... and I can custom it what I want !
How can I use multi route file ? Example : I can define route in App\User\route.user.php , App\Book\route.book.php .... because now, I can only use route file in route folder default !
I do not understand properly question 1. But for question 2, try this:
Go to app/Providers/RouteServiceProvider.php. Look for the function mapWebRoutes(). The line
require base_path('routes/web.php');
Duplicate it and change so you now have :
require base_path('routes/web.php');
require base_path('app/User/route.user.php');
require base_path('app/Whatever/route.whatever.php');
And laravel will load all routes within those files. Now, I've tested this, it works (Laravel 5.3) but I can't guarantee anything or if there are going to be conflicts with routes (duplicates). But yeah, it works.

Optional routes with dashes

I want to create 3 different routes like this:
Route::get('schedule',['as'=>'schedule.view','uses'=>'ScheduleController#view']);
Route::get('schedule/{year}-{month}',['as'=>'schedule.view','uses'=>'ScheduleController#view'])
->where('year','\d{4}')
->where('month','0[1-9]|1[0-2]');
Route::get('schedule/{year}-{month}-{day}',['as'=>'schedule.view','uses'=>'ScheduleController#view'])
->where('year','\d{4}')
->where('month','0[1-9]|1[0-2]')
->where('day','0[1-9]|[12][0-9]|3[01]');
i.e., you can provide one of:
no year/month/day
year & month
year, month & day
The routes work as-is when I link to them with route('schedule.view', ['2015','01','01]) but if I omit the parameters it tries linking to /schedule/{year}-{month}-{day} (with the braces actually in there!).
Is there a way to get laravel to behave smarter or do I have to give each my routes a different name?
It's definitely not possible that way because route() reads them out of an array indexed by name.
One route per name. So it looks like only the last route will be in that array and the others get overriden.
The function that returns the route does nothing else than:
return isset($this->nameList[$name]) ? $this->nameList[$name] : null;
So a different name seems to be the way to go.

Laravel routing group for muliple domains with wildcards, how to handle domain suffixes?

I have 3 domains which, on my local server, take the format:
mydomainfirst.local
mydomainsecond.local
mydomainthird.local
In my routes.php file, I have the following:
Route::group(array('domain' => '{domain}.{suffix}'), function() {
Route::get('/', 'Primary#initialize');
});
The idea is to take the $domain variable in my controller and extract the first/second/third part from it, which works fine. However, now my site is online, this routing file no longer works and throws a Http-not-found exception. After a while, I have figured that the problem is that the domains have now taken the format mydomainfirst.co.uk. Because there are now 2 parts to the domain suffix, it seems I need to do this:
Route::group(array('domain' => '{domain}.{a}.{b}'), function() {
Route::get('/', 'Primary#initialize');
});
To get it to work. Which is stupid. How can I tell it to just accept any suffix? Is there an 'anything' wildcard I can use?
I have tried a few things like this answer but it doesn't work with route groups.
EDIT: It seems the Enhanced Router package would at least enable me to add a where clause to the route group, but does it solve the problem of how to set a wildcard that will match an indeterminate number of segments? I need something like:
{domain}.{anything}
That will match both:
mydomainfirst.local AND mydomainfirst.co.uk
?
Ok let me first say that the code of this package actually looks good and should work. Even if you can't get it running by installing you could take the files and use the code with your own service provider etc.
But there's also a kind of quick and dirty solution. (Actually the package does it pretty similar, but it looks a lot nicer ;))
First, here's how you can do it for one route:
Route::group(array('domain' => '{domain}.{tld}'), function(){
Route::get('/', 'Primary#initialize')->where('tld', '.*');
});
So the where condition for the route group actually gets set on the individual route.
Of course you don't want to do this for every route inside that group so you can use a simple foreach loop:
Route::group(array('domain' => '{domain}.{tld}'), function($group){
Route::get('/', 'Primary#initialize');
foreach($group->getRoutes() as $route){
$route->where('tld', '.*');
}
});
Note: The loop needs to come after all routes. Otherwise they won't registered and therefore not returned with getRoutes()

SEO-friendly URLs in CodeIgniter without the use of slugs?

Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Access from the SEO-friendly URL should be allowed, but access via the integer should cause a 404 error.
This should also work dynamically, where any integer is automatically converted to a URL-safe version of its corresponding category name.
I've seen a few solutions that use 'slugs'... is there a decent alternative?
Thanks.
I've only been working with CodeIgniter for the past couple of months in my spare time, so I'm still learning, but I'll take a shot at this (be gentle):
There is a url_title() function in the URL Helper (which will need loaded, of course) that will change Foo Bar to foo-bar.
$name = 'Foo Bar';
$seo_name = url_title($name, TRUE);
// Produces: foo-bar
http://codeigniter.com/user_guide/helpers/url_helper.html
The URL helper strips illegal characters and throws in the hyphens by default (underscores, by parameter) and the TRUE parameter will lowercase everything.
To solve your problem, I suppose you could either do a foreach statement in your routes.php file or pass the url_title() value to the URL, rather than the ID, and modify your code to match the url_title() value with its category name in the DB.
Afaik the link between 4 and "foo-bar" has to be stored in the DB, so you'll have to run some queries. This is usually not done via routing in CI. Also routing just points a URL to a controller and function and has little to do with url rewriting.
Why don't you want to use slugs?
You could try storing the search engine friendly route in the database using this method or this one.
I wouldn't recommend throwing a 404. Use the canonical link tag in the instead if your worried about Google indexing both http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html.
But if you really want to I guess you could write a function that is called during the pre_controller hook http://codeigniter.com/user_guide/general/hooks.html that checks to see if the URL has an integer as the second segment then call the show_404() method. Perhaps a better solution when writing this function would be to redirect to the SEO friendly version.
Is there a way (via routing) in CodeIgniter to change:
example.com/category/4 to example.com/category/foo-bar
where Foo Bar is the name of category 4 in the database?
Yes.
Using CI 3,
http://www.codeigniter.com/user_guide/general/routing.html
Use Callbacks, PHP >= 5.3
$route['products/([a-zA-Z]+)/edit/(\d+)'] = function ($product_type, $id)
{
return 'catalog/product_edit/' . strtolower($product_type) . '/' . $id;
};
You can route to call a function to extract the name of the category.
Hope I answered your question and can help more people to like codeigniter as I believe it's speedy and light.
Slugs usage is important to make web application more secure which i think is important.
A better recommendation will be to use route to give you a better solution.
$route['(:any)/method/(:num)'] = 'Class/method';
or
$route['(:any)/method/(:num)'] = 'Class/method/$1';
$route['(:any)/gallery/(:num)'] = 'Class/gallery/$1';
base_url()/business-services/gallery/6
base_url()/travel/gallery/12
how to modify routes in codeigniter
Have fun :)

Resources