skip to Main Content

How can I change this URL generated from submitting the form-

http://localhost:8000/estates?zone=London&type=villa

to this URL:

http://localhost:8000/estates/London/villa

Need to make the URL more friendly for search engines.

I get the zone and villa from input fields in a form in

localhost:8000/estates

When I submit the form I get a URL like this-

localhost:8000/estates?zone=London&type=villa

Instead of above I would like to have this URL when I submit the form-

localhost:8000/estates/London/villa

2

Answers


  1. You should restructure your routes so zone and village become route parameters.

    So, for example, the route for http://localhost:8000/estates/London/villa would be Route::post('/estates/{zone}/{villa}', 'SomeController@action') and in the controller you can inject the zone and village as parameters. So you can use something like this :

    class SomeController {
             public function action(Request $request, string $zone, string $villa){
    
             }
    }
    

    It is described further in the Route parameters section of Routing in Laravel docs.

    Login or Signup to reply.
  2. When you submit the form, it should catch the post data in controller action like this-

    class MyController
    {
        public function create()
        {
            // Your form
        }
    
        public function store()
        {
            // This is where you receive the zone and villa in the request
        }
    }
    

    As you can see you have received the input field in request in your store method, now you can do something like this-

    public function store(Request $request)
    {
        // Your code here
        redirect()->to($request->zone.'/'.$request->villa);
    }
    

    Please make sure you have the routes created for zone and villa otherwise redirecting to a non-existing route/url will not work.

    Create a route like this for your request-

    Route::get('estates/{zone}/{villa}', 'MyController@anotherMethod');
    

    You will have another action method in your controller to receive this zone and villa inputs like this-

    public function anotherMethod($zone, $villa)
    {
        // Access your $zone and $villa here
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search