Home > Software engineering >  How to get parameters from URI/URL string | Laravel
How to get parameters from URI/URL string | Laravel

Time:12-03

There is registered route

Route::get('/{category_slug}/{filter_1?}', [CatalogController::class, 'catalog'])

And I have a list of URIs:

/pen/green
/pen/white
/role/15sm
/role/50sm

So, is there any way to parse the URIs and get the parameters?

I'm looking a Laravel tool and preg_match() is not exactly what I need.

Please, advise.

CodePudding user response:

i recommend you to read Documentation, i think you are looking for Laravel model binding https://laravel.com/docs/8.x/routing#route-model-binding

check the link above

i'll try to explain a little

ill suppose you know about model, you have a database called pens and you have model Pen you can use like this

use App\Models\Pen;

Route::get('/pens/{pen}',['PenController::class', 'getPen');

then in your PenController

public function getPen(Pen $pen)
{
   return $pen;
}

in your request {pen} must be replaced by the pen id/primary-key in your pens table of which you want to fetch

CodePudding user response:

Taking the first of your four example links, the parameters would be available in your controller using :

$request->category_slug // Will give you pen
$request->filter_1 // Will give you green
  • Related