2

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

Pankaj
  • 698
  • 9
  • 21
Fardin Moradi
  • 29
  • 1
  • 7

2 Answers2

1

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
}
Pankaj
  • 698
  • 9
  • 21
  • dud have another q, its work good in search engine ? this q is for im not good in this case! – Fardin Moradi Mar 01 '19 at 02:17
  • Parameter URLs are not good for SEO. So yes, the URL structure like this estates/zone/villa is better. You can read more about this matter here- https://moz.com/blog/15-seo-best-practices-for-structuring-urls – Pankaj Mar 01 '19 at 02:24
0

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.

abhiyanp
  • 73
  • 8
  • dud i forget to write this: i get the zone and villa from input in a from in http://localhost:8000/estates and wanna when they submit form this url http://localhost:8000/estates?zone=London&type=villa change to this url http://localhost:8000/estates/London/villa i will change the q, sry my bad – Fardin Moradi Mar 01 '19 at 01:41