I have a URI I need to pass inside a route to a controller. How do I handle this, or more specifically, how can I pass a string that would typically need to be URL encoded first? Could this be Howhandledy, a regular expression constraint in the route?
String to pass
itm:n#_123445
Route
Route::get('getChildren/{uri}', 'ChildrenController#getChildren');
You can use URL facade to do that.
Full path is Illuminate\Support\Facades\URL or just use \URL since it is added in config/app.php file.
Usage:
URL::to('/getChildren', ['itm:n#_123445']));
Generated url:
http://domain.test/getChildren/itm%3An%23_123445
Handling
Route::get('getChildren/{url}', function ($url) {
dd($url); // itm:n#_123445
});
Hope this helps you
I would recommend updating your table schema to create a unique id for each uri in the DB, if it does not already have one. Instead of passing the full uri as a parameter, you would pass the id instead.
First off,
If you are using this specific format, the browser will understand the # as a reference to an anchor in the page - just like this example: https://laravel.com/docs/7.x/packages#views
and won't pass the number to the backend - as you mention you most likely will have to encode the URL before sending it
Now if you are sure that the backend can receive this format, I would do a preg_match in a middleware (if this format is recurrent) or directly in the controller to extract the numerical id.
preg_match('/itm:n#_(\d*)/', $uri , $matches);
$id = matches[0]
Related
I am creating a simple product search engine in Laravel 5.2. I can use either get or post, whichever can accomplish what I'm wanting, even if I need to do some backend processing then pass the pretty URL to another method to show the products.
My parameters are
- query
- merchant
- brand
- page
- sort
All of these parameters can be used on their own or separately.
I'm wanting to use pretty URLs if at all possible.
Basically I want the URLs to look something like this:
/shop/query/shoes
/shop/query/shoes/brand/nike
/shop/query/sort/price
/shop/merchant/amazon
There can be many different routes formed by these 5 parameters, but they are all optional. So what is the best solution to making this route work how I'm wanting, without coding for every single possible route.
I'm sure I am overlooking something. I've used Zend Framework before and just use a * after shop and then I can pass anything in regardless.
If you need any other information, let me know. I appreciate any help.
Try something like this
Route::get('shop/{params?}', function(Request $request, $params = '') {
// everything after "shop/" will be in $params
// you need to add custom logic to parse and handle $params string
return $params;
})->where('params', '(([a-zA-Z0-9-_]+)\/?)+');
{params?} is Optional Parameter
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value
->where('params', ...) is Regular Expression Constraint
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained
NOTE
Make sure that you tweak (([a-zA-Z0-9-_]+)/?)+ regular expression to cover all of your cases, as this is something that I added to quickly test your examples
For a filtered list web page, I want pass filters in the URI string. I.e.:
index.php/user/search/name/joe/location/UK/gender/male
According to CodeIgniter documentation it will be easy to retrieve the information using the URI Class. http://www.codeigniter.com/user_guide/libraries/uri.html?highlight=uri%20class
My doubt:
In the view, How should I set up the filter form so that it calls a uri string based url (index.php/user/search/name/joe/location/UK/gender/male) instead of a regular POST (or GET) request?
Instead of doing it like that you can structure your query like this,
index.php/user/search?name=joe&location=UK&gender=male
This way you can access the url parameters using $data = $this->input->get() and then access individual items like $data['name'], $data['location'] and $data['gender'].
And it would be also easier to set up the form with get method.
I've built my first RESTful API ever and used Slim as my framework. It works well so far.
Now I have seen a great API Design Guide which explained, the best way to build an API is to keep the levels flat. I want to do that and try to figure out how to build an URI like this:
my-domain.int/groups/search?q=my_query
The /groups part already works with GET, POST, PUT, DELETE and also the search query works like this:
my-domain.int/groups/search/my_query
This is the code I use for the routing in PHP:
$app->get('/groups/search/:query', 'findByName');
I just can't figure out how to build optional parameters with an question mark in Slim. I wasn't able to find anything on Google.
EDIT:
Since the search not seems to be suitable for my scenario I try to show another way of what I want to realize:
Let's say I want to get a partial response from the API. The request should look like that:
my-domain.int/groups?fields=name,description
Not like that:
my-domain.int/groups/fields/name/description
How do I realize that in the routing?
The parameters supplied with the query string, the GET parameters, don't have to be specified in the route parameter. The framework will try to match the URI without those values. To access the GET parameters you can use the standard php approach, which is using the superglobal $_GET:
$app->get('/groups/test/', function() use ($app) {
if (isset($_GET['fields']){
$test = $_GET('fields');
echo "This is a GET route with $test";
}
});
Or you can use the framework's approach, as #Raphael mentioned in his answer:
$app->get('/groups/test/', function() use ($app) {
$test = $app->request()->get('fields');
echo "This is a GET route with $test";
});
Ok I found an example that does what I need on http://help.slimframework.com/discussions/problems/844-instead
If you want to construct an URI Style like
home.int/groups/test?fields=name,description
you need to build a rout like this
$app->get('/groups/test/', function() use ($app) {
$test = $app->request()->get('fields');
echo "This is a GET route with $test";
});
It echoes:
This is a GET route with name,description
Even though it's not an array at least I can use the question mark. With Wildcards I have to use /
You may also have optional route parameters. These are ideal for using one route for a blog archive. To declare optional route parameters, specify your route pattern like this:
<?php
$app = new Slim();
$app->get('/archive(/:year(/:month(/:day)))', function ($year = 2010, $month = 12, $day = 05) {
echo sprintf('%s-%s-%s', $year, $month, $day);
});
Each subsequent route segment is optional. This route will accept HTTP requests for:
/archive
/archive/2010
/archive/2010/12
/archive/2010/12/05
If an optional route segment is omitted from the HTTP request, the default values in the callback signature are used instead.
Search query is not suitable for url parameters, as the search string might contain url separator (/ in your case). There's nothing wrong to keep it as query parameter, you don't have to push this concept everywhere.
But to answer your question, optional parameters are solved as another url:
$app->get('/groups/search/:query', 'findByName');
$app->get('/groups/search/strict/:query', 'findByNameStrict');
EDIT: It seems you want to use Slim's wildcard routes. You just need to make sure there's only one interpratation of the route.
$app->get('/groups/fields/:fields+', 'getGroupsFiltered');
Parameter $fields will be an array.
I am using Yii.
if my url is http://localhost/evengee/event/page/id/2/sfn+master/?tab=3
My real url (file path) is only http://localhost/evengee
How would I obtain, preferably in the view:
full url http://localhost/evengee/event/page/id/2/sfn+master/?tab=3
url without explicit parameters http://localhost/evengee/event/page/id/2/sfn+master/
I know I can split/explode str_replace by the ? and use $_SERVER. Would prefer to use
Yii native methods.
For:
full URL (http://localhost/even/page/id/2/?t=3) use
Yii::app()->request->getUrl(),
URL without parameters (http://localhost/even/page/id/2/ use
Yii::app()->request->getPathInfo().
Second one will give you the URL without schema, server and query string. This seems good enough.
To get the full URL, use the getRequestUrl() method of CHttpRequest
Yii::app()->request->getRequestUrl();
You can get the controller, module and action name of the current page from the CApplication methods
Yii::app()->getController()->id; //gets you the controller id
Yii::app()->getController()->getAction()->id; //gets you the action id
You can piece together a URL using the baseURL property of CApplication
Yii::app()->baseURL
The best and shorter way I found is:
Yii::app()->createAbsoluteUrl(Yii::app()->request->getPathInfo());
OR
$this->createAbsoluteUrl(Yii::app()->request->getPathInfo());
For Yii2, use \yii\helpers\Url::canonical().
Documentation: https://www.yiiframework.com/doc/api/2.0/yii-helpers-baseurl#canonical()-detail
The following is a valid REST based URL that can be used to access a resource:
Using codeigniter, how can one access the parameter of 1 that was passed below.
I saw the above in a tutorial and have set up my code. However obviously:
$id = $this->input->get('id');
does not work.
Using $this->input->get('id') would suggest you are sending ?id=1 to the end of the URL. You can use $this->uri->segment(1) but that does not allow for paired uri segments.
If you use $this->get('id') which is a special REST_Controller method then it will pick up either. I did put that in the tutorial you got this image from :)
From the URI Class.
you can use $this->uri->segment(n)
Where n is the segment number you wish to retrieve .