user10124400
user10124400

Reputation:

laravel pass id to controller and display name and phone number in url

I have table contains id, name, city and phone_number, I want to use id to return some data from controller and want to show only the name, city and phone_number in url like this way:

Endpoint: GET /store/sushi-chicago-7736159912/

and from this controller to pass id to controller to return some data

 Route::get('store/{id}','FrontController@getStoreProducts');

Upvotes: 0

Views: 1862

Answers (1)

J. Doe
J. Doe

Reputation: 1732

Store - create and sushi-chicago-7736159912 is slug, it`s my opinion =)

Controller code:

public function getStoreProducts(string $slug)
{
   $explodeSlug = explode('-', $slug);

   $product = Product::where(['name', $explodeSlug[0]])
        ->where(['city', $explodeSlug[1]])
        ->where(['phone', $explodeSlug[2]])
        ->first();
   if (is_null($product)) {
       //throw exception
   }

   return $product
}

Route:

Route::get('store/{slug}','FrontController@getStoreProducts');

Or you may use another way:

Edit route:

Route::get('store/{id}/{slug}','FrontController@getStoreProducts');

Edit method in controller:

public function getStoreProducts(int $id, string $slug)
{
   //in this way you don`t use slug

   $product = Product::where(['id' => $id])
        ->first();

   return $product
}

And now your urls will looks like

/store/41/sushi-chicago-7736159912/

/store/41/sushi%20bar-chicago-7736159912/

Upvotes: 1

Related Questions