Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to define two parameter in laravel route

im using laravel 5.4 and i have a brands and a products table. i want to define two parameter in route and get them in controller or RouteServiceProvider to search.

imagine : site.com/samsung/ => get all products with samsung brand.

and : site.com/samsung/galaxys8 => get all products with samsung brand and galaxys8 model

i can define this using two separate route and controller method : (define route one with 1 parameter{brand} and controller@method1 and define route two with 2 parameters {brand}/{product} and controller@method2)

can i do this better? im a little new in laravel . thank you

Route::get('/{brand}', 'AdvertismentController@show');
Route::get('/{brand}/{product}', 'AdvertismentController@show2');



public function show($brand)
{
        $brands = Advertisment::where('brand' , $brand)->get();
        return $brands;
}

public function show2($brand , $product)
{
    $products = Advertisment::where('product' , $product)->get();
    return $products;
}
like image 673
K1-Aria Avatar asked Jul 24 '17 23:07

K1-Aria


People also ask

How can I create multiple route in Laravel?

Just add another fileGo to your App/Providers/RouteServiceProvider and find the map() method. Here the Service Provider will map your Routes. A quick glance on the file and you will note that API and Web routes are mapped using other methods. * Define the routes for the application.

What is Route parameter in Laravel?

Laravel routes are located in the app/Http/routes. php file. A route usually has the URL path, and a handler function callback, which is usually a function written in a certain controller.

What is prefix in Laravel route?

Route Prefixes The prefix method may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin : Route::prefix('admin')->group(function () { Route::get('users', function () { // Matches The "/admin/users" URL.


2 Answers

I guess that you want to combine the similar controller actions, you can use optional parameters like this:

Route::get('/{brand}/{product?}', 'AdvertismentController@show');

public function show($brand, $product = null)
{
    if (!is_null($product)) {
        $results = Advertisment::where('product' , $product)->get();
    } else {
        $results = Advertisment::where('brand' , $brand)->get();
    }

    return $results;
}
like image 81
Cong Chen Avatar answered Sep 21 '22 20:09

Cong Chen


Just like on this example question here

You pass two arguments on the URI:

Route::get('/{brand}/{product}', 'AdvertismentController@show2');

And on the view:

route('remindHelper',['brand'=>$brandName, 'product'=>productId]);
like image 44
Igor Phelype Guimarães Avatar answered Sep 18 '22 20:09

Igor Phelype Guimarães