Happy Coder
Happy Coder

Reputation: 4702

Limit access to route by parameter value

I have a route like the following :

Route::group([
    'prefix'    => 'reports'
], function () {
     Route::get('/points/{product_name}', ['uses' => 'MyController@get'])->where('product_name', ['product1', 'product2','product3'])
});

So I would like to limit the access to this endpoint id the product name is product1, product2, product3. But with the where clause, I can only see checking with regular expression or a single value.

When I use an array like ['product1', 'product2', 'product3'], but it is throwing an error "message": "Routing requirement for "product_name" must be a string."

How can I solve this?

Upvotes: 2

Views: 178

Answers (3)

Tarun Dhiman
Tarun Dhiman

Reputation: 161

According to laravel docs 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. So you should do as follow:

$allowedParams = implode('|',['product1','product2','product3']);
// it will return you a string as 'product1|product2|product3'
Route::get('/points/{product_name}', ['uses' => 'MyController@get'])
           ->where('product_name', $allowedParams);

Upvotes: 2

Artem
Artem

Reputation: 134

For routes in laravel u can use it like this:

where('product_name', 'product1|product2|product3'])

or whith array:

where('product_name', implode("|", ['product1', 'product2','product3']))

Upvotes: 2

Bulfaitelo
Bulfaitelo

Reputation: 513

You can send with implode(); and to receive using explode();

Send example:

$array_send = ['product1', 'product2', 'product3'];
$imp_send = implode(",", $aray_send);
// return: product1,product2,produtct3

Receive Example:

$array_receive = explode(',', '$product_name');
// return again array

Upvotes: 0

Related Questions