Skip to content
Advertisement

Laravel doubles the route when navigating between navbar links

I have a problem with laravel routes. I have a navbar with the urls /products and /employee. I manage to switch between perfectly perfectly without giving error. However, when I access the link /products/new and from there I try to go back to /products or go to /employees through the navbar, the link is /products/products or /employee/employee. How do I not replicate the links?

Routes

JavaScript

app.blade

JavaScript

index.blade

JavaScript

producs.blade

JavaScript

new_products.blade

JavaScript

componente_navbar.blade

JavaScript

Advertisement

Answer

The problem is with how you have specified your href values on your a links, they are all defined as relative to the current path:

JavaScript

What the above says is; from where I am currently, take me to the employees page. If you’re at the root (/) of your application then the path is /employees. However, if you are anywhere else, the path is /you-are-here/employees.

What you really want to do is use one of the Laravel URL helpers such as url() or route().

I personally favour the route helper as it uses the name you have defined for a route meaning if the path for a given route changes, you only need to change it in your web.php file and don’t have to go searching your code base for instances of /some/path/used/everywhere/.

You define a name for your route on the route definition in your web.php file, so for example:

JavaScript

With a name defined (they must be unique by the way), you can use the name in conjunction with the route() helper:

JavaScript

Now it doesn’t matter how deep you are in your site structure, your link will always take you to /products.

On a side note, seeing as you appearing to be doing CRUDDY operations, you might want to consider using the resource method available on Route. This defines all your common routes and their names for you.

JavaScript

Note that these assume you’re following naming conventions. So rather than /products/new it’s /products/create and your controllers as named {Something}Controller. Follow framework conventions where possible, it will save you and other headaches down the line.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement