আগামী ২৩ অক্টোবর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML,CSS,Bootstrap,PHP,MySQl, AJAX and JQUERY কোর্সের ৮৬ তম ব্যাচ। আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722817591, Email : [email protected] কোর্সের সিলেবাস এর জন্য এখানে ক্লিক করুন ।

Laravel 5.4 Tutorial Part-3: Laravel Routes and Definations

What is Laravel Routes?

Simply, Laravel routes are just how Laravel respond to URL’s request. All Laravel routes are defined in the routes/web.php file, which is automatically loaded by the framework. Routing is the core components of Laravel framework. It looks a little complex at first, but once you get comfortable with basics you will be amazed by this feature of Laravel.

To work with Laravel routes, you should open routes/web.php file in your Laravel project and. All Laravel routes are written there.
Imagine if you have: Home, About and a Contact page for your site. The users might look for those page like this;

for Home page:

http://localhost:8000/

for About page:
http://localhost:8000/about

for Contact page:
http://localhost:8000/contact

What’s a Closure?

Closures are PHP’s version of anonymous functions. A closure is a function that you can pass around as an object, assign to a variable, pass as a parameter to other functions and methods, or even serialize.

So in Laravel routes file, you can write it like this;

Route::get('/', function (){
    echo "<h2>This is Home Page</h2>;
});
Route::get('/about', function (){
    echo "<h2> This is About Page</h2>";
});
Route::get('/contact', function (){
    echo "<h2> This is Contact Page</h2>";
}); 
laravel home page

laravel home page

Laravel Contact Us Page

Laravel Contact Us Page

laravel about page

laravel about page

HTTP Methods

If you’re not familiar with the idea of HTTP methods, read on in this chapter for more information, but for now, just know that every HTTP request has a “verb,” or action, along with it. Laravel allows you to define your routes based on which verb was used; the most common are GET and POST, followed by PUT, DELETE, and PATCH.
Each method communicates a different thing to the server, and to your code, about the intentions of the caller.

Route Verbs

You might’ve noticed that we’ve been using Route::get in our route definitions. This means we’re telling Laravel to only match for these routes when the HTTP request uses the GET action. But what if it’s a form POST, or maybe some JavaScript sending PUT or DELETE requests? There are a few other options for methods to call on a route
definition, as illustrated below:

Route::get('/', function () {
return 'Hello, World!';
});
Route::post('/', function () {});
Route::put('/', function () {});
Route::delete('/', function () {});
Route::any('/', function () {});
Route::match(['get', 'post'], '/', function () {});

In laravel you can fire mysql queries in ‘Route’ also without any controller or model.

Connect Database:

To connect database in Laravel, you can utilizes the .env PHP library by Vance Lucas. In a fresh Laravel installation, the root directory of your application will contain a .env.example file. If you install Laravel via Composer, this file will automatically be renamed to .env. Otherwise, you should rename the file manually.

laravel database-connection in env file

laravel database-connection in env file

For example

Route::get('/getData', function()
{
$fetchData = DB::select('select * from users where id = ?', array(1));
echo "<pre>";
print_r($fetchData);
echo "</pre>";
});

Laravel Database Query in Routes

Laravel Database Query in Routes

Route::get($uri, $callback)

We already have seen the example of a get route. It is typically used for reading an item.

Route::get('foo', function () {
echo 'GET Method';
});

laravel Route Get Method Example

laravel Route Get Method Example

Route::post($uri, $callback)

To hit the post route, we actually need to create a form inside the get route. In the form the method should be post and the action should be the uri of the post route.

Route::post('foo', function(){
 print_r($_REQUEST);
});

Route::get('foo', function(){
 echo '<form method="POST" action="foo">';
 echo 'Enter Name:<input type="text" name="name">';
 echo '<input type="submit">';
 echo csrf_field();
 echo '</form>';
 
});
Laravel Route Post Method Example

Laravel Route Post Method Example

Laravel Route Post Method Output Example

Laravel Route Post Method Output Example

Note: Before closing Form method you need to add csrf_field() for avoiding token missmatch error

Route::put($uri, $callback)

PUT when you need to replace the state of some data already existing on that system. As all the browsers only knows about the put method. So to hit the put method we need to add a hidden input to the form like this.

Route::put('update', function()
{
$name=$_REQUEST['name'];
$id=$_REQUEST['id'];
$affected = DB::update("UPDATE users set name='$name' where id = ?", [$id]);
echo $affected==1?"Successfully Updated":"UPdate Fail";
});

Route::get('update', function(){
$fetchData = DB::select('select * from users where id = ?', array(1));
echo '<form method="POST" action="update">';
echo "Update Name: <input type=\"text\" name=\"name\" value=\"{$fetchData[0]->name}\">";
echo "<input type=\"hidden\" value=\"{$fetchData[0]->id}\" name=\"id\">";
echo '<input type="hidden" value="PUT" name="_method">';
echo '<input type="submit">';
echo csrf_field();
echo '</form>';
});

Laravel Put Mehtod Example

Laravel Put Mehtod Example

Laravel Put Mehtod Update Example

Laravel Put Mehtod Update Example

Route::delete($uri, $callback)

DELETE when you need to delete a resource (relative to the URI you’ve sent) on that system. The delete method also need a hidden input, but the value should change to DELETE.

Route::delete('delete', function()
{
$id=$_REQUEST['id'];
$affected = DB::update("DELETE FROM users where id = ?", [$id]);
echo $affected==1?"Successfully Deleted":"Delete Fail";
});

Route::get('delete', function(){
$fetchData = DB::select('select * from users where id = ?', array(1));
echo '<form method="POST" action="delete">';
echo "Enter User Id for Delete: <input type=\"text\" name=\"id\">";
echo '<input type="hidden" value="DELETE" name="_method">';
echo '<input type="submit" value="Delete">';
echo csrf_field();
echo '</form>';
});

Laravel Delete Request Method Example

Laravel Delete Request Method Example

Laravel Delete Request Method Example

Laravel Delete Request Method Example

Route Handling with Controller

As you’ve probably guessed, passing a closure to the route definition is not the only way to teach it how to resolve a route. Closures are quick and simple, but the larger your application gets, the clumsier it becomes to put all of your routing logic in one file. Additionally, applications using route closures can’t take advantage of Laravel’s route caching (more on that later), which can shave up to hundreds of milliseconds off of each request.
The other common option is to pass a controller name and method as a string in place of the closure, as in

Route::get('/', '[email protected]');

This is telling Laravel to pass requests to that path to the index() method of the App\Http\Controllers\WelcomeController controller. This method will be passed the same parameters and treated the same way as a closure you might’ve alternatively put in its place.

Fetch data From your Database in Laravel Controllers

Laravel provide more controllers features. In laravel you can fire mysql queries in your Controllers also without any route or model.

Connect Database:

To use database in your Laravel Controllers you want to add namespace by using “use” key work, as like:

use DB;

see the full example and sample output:

<?php

namespace test\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use test\Http\Requests;

class homeController extends Controller
{
    //

    public function index(){
    	$students = DB::table('students')->get();
    	return view('test',['students'=>$students]);
    }
}

Now create test.php file in resources\views\ folder like this example

 <?php
 foreach($students as $student){
 	echo $student->name,"<br>";
 }
 ?>

Now, you can execute “http://localhost:8000” url in your browser, and you’ll get output as like:

Controllers with database connection

Controller with database connection

Passing parameter to controller from route in laravel

First modify your route as like:

Route::get('/{param}', '[email protected]');

Now go to your index function in homeController and modify index function as like:

<?php

namespace test\Http\Controllers;
use Illuminate\Http\Request;
use test\Http\Requests;

class homeController extends Controller
{
    public function index($param){
    	return $param;
    }
}

Now, you can execute “http://localhost:8000/Hello Bangladesh” url in your browser, and you’ll get output as like:

Passing Data From Router to Controller

Passing Data From Router to Controller

Laravel Route Parameters

Of course, sometimes you will need to capture segments of the URI within your route. There are two ways by which we can capture the parameters passed with the URL.

  • Required Parameters
  • Optional Parameters

Required Parameters

These parameters must be present in the URL. For example, you may need to capture a user’s Name from the URL. You may do so by defining route parameters. let’s do learn it by writing an example.

You might want to capture students name from url:

// get the parameter of name
Route::get('students/{name}', function($name) {
        echo 'Students Name is ' . $name;
}); 

Now in your browser, you can access the student name like this

“http://localhost:8000/students/Masud”.

laravel routes parameter

laravel routes parameter

Optional Parameters

There are some parameters which may or may not be present in the URL and in such cases we can use the optional parameters. The presence of these parameters is not necessary in the URL. These parameters are indicated by “?” sign after the name of the parameters. Here is the sample coding for web.php file for that purpose.

Route::get('users/{name?}', function($name="Masud Alam") {
        echo 'User Name is ' . $name;
});
laravel route optional parameter

laravel route optional parameter

Above picture, it will execute the 3rd method and the optional argument/parameter name will be passed to the variable $name. The last argument ‘Sohel’ is optional. If you remove it, the default name will be used that we have passed in the function as ‘Masud Alam’

Regular Expression Constraints

You may constrain the format of your route parameters using the where method on a route instance. 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) {
    echo "Your name: $name";
})
->where('name', '[A-Za-z]+');

Route::get('test/{id}', function ($id) {
    echo "Your Id: $id";
})
->where('id', '[0-9]+');

Route::get('test/{id}/{name}', function ($id, $name) {
    echo "Your Id: $id and Name: $name";
})
->where(['id' => '[0-9]+', 'name' =>'[a-z]+']);


Laravel Routing with Regular Expressions

Laravel Routing with Regular Expressions

Global Constraints

If you would like a route parameter to always be constrained by a given regular expression, you may use the pattern method. You should define these patterns in the boot method of your RouteServiceProvider:

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::pattern('id', '[0-9]+');

    parent::boot();
}

Once the pattern has been defined, it is automatically applied to all routes using that parameter name:

Route::get('user/{id}', function ($id) {
    // Only executed if {id} is numeric...
});

Route Names

The simplest way to refer to these routes elsewhere in your application is just by their path. There’s a url() helper to simplify that linking in your views. The helper will prefix your route with the full domain of your site.

Example: URL Helper

<a href="<?php echo url('/'); ?>">

// outputs <a href="http://myapp.com/">

However, Laravel also allows you to name each route, which enables you to refer to it without explicitly referencing the URL. This is helpful because it means you can give simple nicknames to complex routes, and also because linking them by name means you don’t have to rewrite your frontend links if the paths change.

Example: Defining route names

// Defining a route with name in routes/web.php:
Route::get('members/{id}', '[email protected]')->name('members.show');

// Link the route in a view using the route() helper
<a href="<?php echo route('members.show', ['id' => 14]); ?>">

This example illustrates a few new concepts. First, we’re using fluent route definition to add the name, by chaining the name() method after the get() method. This method allows us to name the route, giving it a short alias to make it easier to reference elsewhere.

In our example, we’ve named this route members.show; resourcePlural.action is a common convention within Laravel for route and view names.

We also introduced the route() helper. Just like url(), it’s intended to be used in views to simplify linking to a named route. If the route has no parameters, you can simply pass the route name: (route('members.index')) and receive a route string http://myapp.com/members/index). If it has parameters, pass them in as an array as the second parameter like we did in this example.

In general, I recommend using route names instead of paths to refer to your routes, and therefore using the route() helper instead of the url() helper. Sometimes it can get a bit clumsy—for example, if you’re working with multiple subdomains—but it provides an incredible level of flexibility to later change the application’s routing structure without major penalty.

Passing Route Parameters to the route() Helper

When your route has parameters (e.g., users/{id}), you need to define those parameters when you’re using the route() helper to generate a link to the route.

There are a few different ways to pass these parameters. Let’s imagine a route defined As:

Route::get('users/{usuerId}/comments/{commentId}', '[email protected]')->name('users.comments.show');

If the user ID is 1 and the comment ID is 2, let’s look at a few options we have available to us:

Option 1:

route('users.comments.show', [1, 2])
// http://myapp.com/users/1/comments/2

Option 2:

route('users.comments.show', ['userId' => 1, 'commentId' => 2])
// http://myapp.com/users/1/comments/2

Option 3:

route('users.comments.show', ['commentId' => 2, 'userId' => 1])
// http://myapp.com/users/1/comments/2

Option 4:

route('users.comments.show', ['userId' => 1, 'commentId' => 2, 'opt' => 'a'])
// http://myapp.com/users/1/comments/2?opt=a

As you can see, nonkeyed array values are assigned in order; keyed array values are matched with the route parameters matching their keys, and anything left over is added as a query parameter.

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor's degree in Engineering from State University Of Bangladesh, I'm also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i'm a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I'm also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute - a leading Training Institute in the country.

Leave a Reply

Your email address will not be published. Required fields are marked *