Laravel Routing Basics
# CHAPTER 4
Laravel Routing Basics
1. Introduction
In core PHP, if a user wanted to visit an "About Us" page, they had to type the exact physical file path into their browser (e.g.,www.site.com/about.php). In modern frameworks, URLs are completely decoupled from physical files. This is managed by the Router. In this chapter, we will learn how to intercept incoming URLs, create clean, SEO-friendly web addresses, and pass dynamic parameters.
2. Learning Objectives
By the end of this chapter, you will be able to:- Define basic GET and POST routes.
- Return a View directly from a route.
-
Capture dynamic URL parameters (e.g.,
/user/5).
- Use Named Routes to prevent broken links.
3. Beginner-Friendly Explanation
Imagine a switchboard operator at a massive corporate headquarters. When you call the company, you don't dial the CEO's direct desk phone. You dial the main public number. The operator answers and asks, "Who do you want to speak with?" If you say "Sales," she unplugs your wire and plugs it into the Sales department. If you say "Support," she plugs you into Support. In Laravel,routes/web.php is the switchboard operator. Every single time a user types a URL (like /about or /contact), Laravel checks the web.php file to see where that URL should be "plugged in."
4. Basic Routing (GET and POST)
All your web routes live in theroutes/web.php file.
Laravel's Route class accepts two arguments: the URL pattern, and a "Closure" (an anonymous function) that executes when someone visits that URL.
A GET Route (Visiting a page):
Returning a View: Instead of plain text, we usually return a beautiful HTML View.
5. Dynamic Route Parameters
What if you have 10,000 user profiles? You cannot manually write a route for/user/1, /user/2, etc. You must capture the ID dynamically using {} curly braces.
6. Fallback Routes (Custom 404 Pages)
If a user types a URL that doesn't exist (/super-secret-page), Laravel throws a 404 error. You can intercept this and show a custom error page.
7. Named Routes (The Best Practice)
Imagine you have an HTML link to your profile page:<a href="/user/profile">Profile</a>.
Later, your boss says, "Change the URL to /account/profile." You now have to search through 50 HTML files and change every single link manually!
Named Routes solve this. You assign a nickname to a route.
In web.php:
In your HTML (Blade) View:
*Why this is magic:* If your boss changes the URL to /my-cool-account, you only change it in web.php. Because the HTML link relies on the nickname (profile.show), every single link on your website instantly updates automatically!
8. Backend Workflow: Routing to a Controller
In the real world, you do not write massive functions insideweb.php. It gets too messy. The Router's only job is to point the traffic to a Controller.
*(We will cover this deeply in the next chapter).*
9. Best Practices
-
Always Use Named Routes: Never hardcode URLs like
<a href="/about">in your views. Always use<a href="{{ route('about') }}">. It will save you from catastrophic link breakage when you redesign your site.
10. Common Mistakes
-
Method Not Allowed Error: If you create an HTML form with
method="POST", but yourweb.phpfile defines the route asRoute::get('/submit'), Laravel will crash and throw a405 Method Not Allowedexception. POST traffic must be caught by aRoute::post().
11. Exercises
-
1.
Write a dynamic route that captures a string
{category}and a number{id}, and returns text saying: "Viewing Category: X, Item: Y".
12. Coding Challenges
-
Challenge: Open
routes/web.phpin a Laravel project. Create a route for/contactthat returns a view. Name the routecontact.us.
13. MCQs with Answers
In which file do you define the URLs for standard web pages in a Laravel application?
What is the primary benefit of using "Named Routes" (e.g., ->name('profile')) in Laravel?
14. Interview Questions
- Q: Explain how dynamic routing parameters work in Laravel. How do you pass an ID from the URL into the route's closure or controller?
-
Q: Differentiate between
Route::getandRoute::post. Give an example of a user action that would require each.
15. FAQs
Q: I see a file calledapi.php in the routes folder. What is that?
A: Laravel separates web traffic (humans using browsers) from API traffic (mobile apps asking for JSON). web.php automatically applies Sessions and CSRF security, which browsers need. api.php is lightweight and stateless, designed strictly for JSON responses.
16. Summary
In Chapter 4, we took control of our application's traffic. Theroutes/web.php file acts as the ultimate switchboard operator, catching every incoming URL and deciding what happens next. By utilizing dynamic parameters, we can serve thousands of unique profiles with a single line of code. By enforcing the use of Named Routes, we guarantee our application's links will never break, no matter how often we redesign our URLs.