One of the amazing features of Laravel is its Routing.
Before using Laravel framework I have used Codeigniter framework where all routing can be done by controller, however in Laravel you can see a overall view of your application by looking at the Routing file.
In Laravel all requests are mapped with the help of routes. You can see all linked controllers & then respective views & models in the application. So for a Developer/Programmer it's easy to search the files in a application by the url.
In this post you will get basic understanding of everything about routing in Laravel. Then you can go in detail once you have a clear understanding of Routing basic.
Before going into the Routing Concept, If you are following along with this tutorial, Make sure you have Latest version of Laravel Installed.
How to Install Laravel 5.5 with XAMPP on Linux
I have created a new Laravel application named blog for this tutorial. Let's get started to understand the Routing concept by example in this application.
In Laravel 5.7, all the application routes are registered within the app/Routes/web.php
file. In following snapshot you can see the directory structure of laravel 5.7 & it's route file.
Basic Routing
As you can see the blog homepage, this is nothing but the default welcome view which has been defined in routes/web.php
.
Let’s look at an example route:
Open app/routes/web.php
Route::get('/', function () {
return view('welcome');
});
The above route / responds to home page. It uses an anonymous function and returns the view named welcome, you can find the welcome view in resources/views/welcome.blade.php.
let's understand what is blade.php in view file?
Blade is the template engine provided in Laravel. Blade template engine does not restrict from using plain PHP code in views. View files in Laravel use the .blade.php file extension and are typically stored in the resources/views
directory. But you can store views in custom folder as per your requirement.
open resources/views/welcome.blade.php.
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet" type="text/css">
<!-- Styles -->
<style>
html, body {
background-color: #fff;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 200;
height: 100vh;
margin: 0;
}
.full-height {
height: 100vh;
}
.flex-center {
align-items: center;
display: flex;
justify-content: center;
}
.position-ref {
position: relative;
}
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.content {
text-align: center;
}
.title {
font-size: 84px;
}
.links > a {
color: #636b6f;
padding: 0 25px;
font-size: 13px;
font-weight: 600;
letter-spacing: .1rem;
text-decoration: none;
text-transform: uppercase;
}
.m-b-md {
margin-bottom: 30px;
}
</style>
</head>
<body>
<div class="flex-center position-ref full-height">
@if (Route::has('login'))
<div class="top-right links">
@auth
<a href="{{ url('/home') }}">Home</a>
@else
<a href="{{ route('login') }}">Login</a>
@if (Route::has('register'))
<a href="{{ route('register') }}">Register</a>
@endif
@endauth
</div>
@endif
<div class="content">
<div class="title m-b-md">
Laravel
</div>
<div class="links">
<a href="https://laravel.com/docs">Documentation</a>
<a href="https://laracasts.com">Laracasts</a>
<a href="https://laravel-news.com">News</a>
<a href="https://nova.laravel.com">Nova</a>
<a href="https://forge.laravel.com">Forge</a>
<a href="https://github.com/laravel/laravel">GitHub</a>
</div>
</div>
</div>
</body>
</html>
In above code you can see this is your home page view. To customize this page either you have to create a new view & call it in controller or you can edit this welcome.blade.php
as per your requirement.
Basic Routing
All the routes in web.php
can be accessed by entering the route's url in the browser.
Example 1:
you may access the following route by navigating to http://127.0.0.1:8000/news in url . I am running http://127.0.0.1:8000 for my application.
For you the url may be different.You can set your custom host in virtual-host & can navigate your route. But whatever the url for your application it is , just put news after that. The route will return Test news as in following route.
Route::get('/news', function () {
return "Test news";
});
Example 2
Lets create a route named as event which will call an EventController & will return the welcome view. I have not created any other view. you can create any view as welcome.blade.php
& can return that view.
create a controller :
php artisan make:controller EventController
Now our controller has been created. You can check the controller in your application directory.
Let's define route in web.php
.
Route::get('/event', 'EventController@index');
In this route you can access this by event after your baseurl as http://127.0.0.1:8000/event & it will call EventController & will return the view as defined in index method of EventController.
so open app/Http/Controllers/EventController.php
& create a new method index()
in EventController as follows.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class EventController extends Controller
{
public function index(){
return view('welcome');
}
}
Type http://127.0.0.1:8000/event
in url & you can see the welcome view.
Let's see some more examples of Routes
View Routes
If you want to return view only then you can use Route:view()
Example: If you want to return welcome view in route the code is as follows.
Route::view('/welcome', 'welcome');
Here 1st parameter is /welcome is is the path & 2nd parameter welcome is the view name.
Type http://127.0.0.1:8000/welcome in browser.
Note: Like get method you can use post method in Route based upon your request method.
Route::match()
Sometimes you may need to register a route which will respond multiple http verbs. Muliple verbs are like get & post.
Example:
Route::match(['get', 'post'], '/', function () {
return "Test GET/POST Route";
});
Route::any()
Except Route:match() you may even register a route that responds to all HTTP verbs using the any
method as follows.
Route::any('/anynews', function () {
return "Testing any http verb Route";
});
Type http://127.0.0.1:8000/anynews in url. It will return the text Testing any http verb Route as in Route.It will call the anynews whatever the http verb may be.
For redirecting Route you may use Route:redirect(). In this post we have already created routes as news & event.Let's redirect route news to route event as follows.
Route::redirect('/news', '/event');
So here if you will enter url as http://127.0.0.1:8000/news it will redirect to http://127.0.0.1:8000/event.
Accessing Route Parameters:
a. Required Route Parameters
Now that we have some really basic routing setup, let’s start accepting parameters to our routes. In order to understand route parameters let's see the following example:
Route::get('news/{id}', function($id)
{
return "News id is:".$id;
});
So here if you will enter any id in url followed by news you can get that id. See the following snapshot
Here i entered 1 as news id & you can see the ouput as News id is: 1
On visiting http://127.0.0.1:8000/news/29 you will get result as
News id is:29
You may define as many route parameters as required by your route as below:
Route::get('news/{id}/comments/{comment}', function ($id, $comment) {
return "News id is: ".$id." And Comments is: ".$comment;
});
Here you can see there are two parameters in function $id & $comment .You can define as many parameters as per your requirement
b. Optional Route Parameter
Adding a ? to the wildcard and assigning null to the closure argument will allow the parameter to be optional, otherwise you’ll get an error if you don’t include the parameter.
Route::get('user/{name?}', function ($name = null) {
return "Hi ".$name;
});
If you will visit http://127.0.0.1:8000/user you will get the result as Hi because here the parameter is optional & you can execute the url without parameter.
Now let us pass a parameter as follows.
Also you can set default value to parameter & in case you are ot passing any value to parameter the default value will come in result.
Route::get('user/{name?}', function ($name = 'Smith') {
return "Hi ".$name;
});
Here i have not passed any value for name parameter but its showing default name Smith as we have taken smith name as default name.
Regular Expression Constraints:
You may constrain the format of your route parameters using the where method. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained:
Route::get('test/{name}', function ($name) {
return "Hi ".$name;
})->where('name', '[A-Za-z]+');
Here the name parameter will accept only as per the regular expression.It can't accept digits. You can see as follows.
Now let's input value as per regular expression.
This all are the basics of Routing. Once you understand the basics you can go for other routing in details.
Fantastic Job Done ! Have fun working with Laravel Basic Routes.