Ad

Laravel: Change Result Of Input Query To Friendly Url

- 1 answer

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

Ad

Answer

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}', '[email protected]');

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
}
Ad
source: stackoverflow.com
Ad