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.
Related
Is it possible to create a one time link in Laravel? Once you open the link it expires?
I have created a Temporary Signed Link, but I can open it multiple times. How do I counter it?
There is this package that can help you
https://github.com/linkeys-app/signed-url/
This will generate a link valid for 24hours and for just one click .
$link = \Linkeys\UrlSigner\Facade\UrlSigner::generate('https://www.example.com/invitation', ['foo' => 'bar'], '+24 hours', 1);
The first time the link is clicked, the route will work like normal. The second time, since the link only has a single click, an exception will be thrown. Of course, passing null instead of '+24 hours' to the expiry parameter will create links of an indefinite lifetime.
There maybe a package that provides a functionality like this... always worth looking on Packagelist before building something rather generic like this from scratch. But, it's also not a hard one to build from scratch.
First you'll need database persistence, so create a model and a migration called UniqueLink. In the migration you should include a string field called "slug", a string field called path, and a timestamp field called "used_at."
Next create a controller with a single __invoke(string $slug) method. In the method look up the $link = UniqueLink::where('slug', $slug)->first(); Update the models' used_at parameter like so $link->update(['used_at' => Carbon::now()]);
Then return a redirect()->to($link->path);
Add a route to your routes file like this Route::get('/unique-link/{slug}', UniqueLinkController::class);
Now you'll just need to create a method to add these links to the db which create a slug (you could use a UUID from Str::uuid() or come up with something more custom) and a path that the link should take someone. Over all a pretty straight forward functionality.
You could track when the URL is visited at least once and mark it as such for the user if you really want to, or you could reduce the expiry down to a few mins.
URL::temporarySignedRoute( 'foobar', now()->addMinutes(2), ['user' => 100] );
I get from ctf0/media-manager the link to a chosen file, like
http://example.com/folder1/mypic.jpg
In my database I want only save
/folder1/mypic.jpg
because I know the domain, it's every time my one.
I need to cut the first letters flexible by counting the letters from my .env in my controller.
Maybe I want to change the domain to http://productive-example.com later, then the letters are different.
Sorry for my bad english, I hope you understand the problem.
You can use PHP's parse_url function if you would like:
$url = 'http://something.com/some/path/file.jpg';
$path = parse_url($url, PHP_URL_PATH);
// "/some/path/file.jpg"
PHP.net Manual - Function parse_url
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.
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 :)
Playing with the new(ish) url rewriting functionality for web forms, but I'm running into trouble trying to declare parameters as optional.
Here's the scenario. I've got a search function which accepts two parameters, sku and name. Ideally I'd like the URL for this search function to be /products/search/skuSearchString/nameSearchString. I also have various management pages that need to map to things like /products/management/ or /products/summary/. In other words, the last two parameters in the URL need to be optional - there might be one search string, or two, or none.
This is how I've declared my virtual URL:
Friend Const _VIRTUALURL As String = "products/{action}/{sku}/{*product}"
And added the following defaults:
Me.Defaults = New Web.Routing.RouteValueDictionary(New With {.sku = "/"})
Me.Defaults = New Web.Routing.RouteValueDictionary(New With {.product = "/"})
I have two problems with this setup. The most pressing is that the url seems to expect an sku parameter. So, /products/summary/ cannot be found but /products/summary/anyTextAtAll/ maps to the correct page. You get the same result whether the defaults are set to "/" or "". How do I ensure both sku and product parameters are optional?
The second is more a matter of interest. Ideally, I'd like the url to be able to tell whether or not it's got a product search string or a url search string. The obvious way to do this is to make one or the other default to a value I can just pick up and ignore, but is there a neater way of handling it?
I'm not sure I entirely understood the question, but I have some comments about what you've shown so far:
The manner in which you're setting defaults seems incorrect. You're first setting a default value dictionary with a value for "sku". You're then replacing the default value dictionary with a value for "product".
A default value of "/" is unlikely to be what you want. In this case it sounds like you want a default value of just "" (empty string).
Try something like:
Me.Defaults = New Web.Routing.RouteValueDictionary(New With {
.sku = "",
.product = "" })
My VB skills are rather weak, so the syntax I showed might not be exactly right.
I think that if you change both of these then you should be good to go.