Category Archives: Laravel Tutorial

Laravel HTTP Session


Laravel HTTP Session – The Laravel HTTP Session is used to store information about the user requests. Laravel provides many driver to handle session data.


Laravel HTTP Session.

Let us understand how to use laravel Http Session.

Function:-

There are some followings function available in laravel Http Session.

  • 1. Introduction.
  • 2. Using The Session.
  • 3. Adding Custom Session Drivers.

1. Introduction.

It is used to store information about user requests. Laravel provides various drivers like file, cookie, apc, array, Memcached, Redis and database. by default file driver is used because it is lightweight.

Configuration

Session is configured in the file stored at config/session.php. laravel is configfure to use the file session driver which is work well for many application.

file– session are stored in storage/framework/sessions.
cookie– session are save in secure, encrypted cookies.
database– session are save in a relational database.
memcached/redis– session are save in one of these fast,cache based store.
array– session are store in a PHP array.

Driver Prerequisites

Database

Before using the database session driver. WE have to need to create table to contain the session items.

Schema::create('sessions', function ($table) {
    $table->string('id')->unique();
    $table->unsignedInteger('user_id')->nullable();
    $table->string('ip_address', 45)->nullable();
    $table->text('user_agent')->nullable();
    $table->text('payload');
    $table->integer('last_activity');
});

You can also use the session:table Artsian command to generate this table.

php artisan session:table

php artisan migrate

Redis

Before using Redis session in Laravel. We will need to install the predis/predis package via composer. You can configure your Redis connection in the database configuration file.

2. Using The Session.

Retrieving Data

There are two way to access session data first is global session helper and second one is request instance. Using request instance we can use the get() method, which will take one argument.

session()->get('key', 'default');
        return 'default';
    }
}

The Global Session Helper

We can use global session php function to access and store data in the session. When the session helper is called with single argument it will return the value of that session key.

Route::get('home', function () {
    
    $value = session('key');

    $value = session('key', 'default');

    session(['key' => 'value']);
});

Retrieving All Session Data

If you want to access all data in the session. You can use all method.

$data = $request->session()->all();

Determining If An Item Exists In The Session

The has method is used tp check value is present in session or not. If value is present then this function will return true. Otherwise it will return null.

if ($request->session()->has('users')) {
    return true;
}

If the value is null. Then you may use exists method.

if ($request->session()->exists('users')) {
    return true;
}

Storing Data

To store data in the session, you can use put method.

$request->session()->put('key', 'value');

session(['key' => 'value']);

Pushing To Array Session Values

The push method can be used to push a new value on a session value that is an array.

$request->session()->push('user', 'Players');

Retrieving & Deleting An Item

The pull method is used to retrieve and delete item from the session in single statement.

$value = $request->session()->pull('key', 'default');

Flash Data

Sometimes you want to store items in the session only for next request. You can use flash method. Flash data is primarily usefull for short-lived status message.

$request->session()->flash('status', 'Task was successful!');

Deleting Data

The forget method will remove a piece of data from the session. If you want to remove all data from the session you can use flush method.

$request->session()->forget('key');

$request->session()->flush();

Regenerating The Session ID

Laravel automaticallt regenerate session id when we use LoginController. If you need to manually regenerate session id, you can use regenerate method.

$request->session()->regenerate();

Full Example Using The Session:-

Create a controller page called SessionController by using Artsian command.

php artisan make:controller SessionController --plain
Laravel HTTP Session

Controller Parts:-

Let’s look at a simple example.

session()->put('name','Sonu Kumar');
      echo "Data has been added to session";
     }
	 public function accessSessionData(Request $request)
	 {
      if($request->session()->has('name'))
         echo $request->session()->get('name');
      else
         echo 'No data in the session';
     }
  
   public function deleteSessionData(Request $request)
   {
      $request->session()->forget('name');
      echo "Data has been removed from session.";
   }
	
	
}

Route Path:-

Route::get('set','SessionController@storeSessionData');
Route::get('get','SessionController@accessSessionData');
Route::get('remove','SessionController@deleteSessionData');

Output of set Url is:-

Laravel HTTP Session

Output of get Url is:-

Laravel HTTP Session

Output of remove Url is:-

Laravel HTTP Session

3. Adding Custom Session Drivers.

Implementing The Driver

The custom session driver should implement the SessionHandlerInterface. Just a few simple methods we need to implement.

Let’s look at a simple example.


The open method is used in file based session store system.
The close method is also used for disregarded.
The read method should return the string version of session data.
The write method should return write the given data string associate with session id.
The destroy method should remove the data with session id from storage.
The gc method should destroy all session data.

Registering The Driver

To add additional driver to laravel session backend, you can use the extend method on the session facade. You should call the extend method from the boot method of a service provider.

Let's look at a simple example.


Once the session driver has been registered, you can use the mongo driver in your config/session.php configuration file.

Laravel Views


Laravel Views – The Laravel Views is used to seperated the application logic and the presentation logic. In MVC farmework, V stand for view. Views file stored in resource/views directory.


Laravel Views.

Let us understand how to use laravel views.

Function:-

There are some followings function available in laravel views.

  • 1. Creating Views.
  • 2. Passing Data To Views.
  • 3. View Composers.

1. Creating Views.

Views contain the HTML derved by your application and seperated your controller/application logic from your presentation logic. A simple view may be look like this:-

Views must be save as the extension .blade.php.

Views part:-

        

Hello, {{ $name }}

Route Path:-

Route::get('index', function () {
    return view('greeting', ['name' => 'Sonu']);
});

You can see the first argument pass to the view helper corresponding to the name of the view file. The second argument is the array of data that should be display on the view part.

Determining If A View Exists

If you have to need to determine if a view exists, you can use the view facade. The exists method will return true if the view exists.

use Illuminate\Support\Facades\View;

if (View::exists('emails.customer')) 
{
   return true;
}

2. Passing Data To Views.

As you notice in previous example. We passed an array of data to views:-

return view('greetings', ['name' => 'Sonu']);

When we passing data in this format. Then you can acces like this:-

If you are passing a complete array of data to the view helper function, you may use the with function.

return view('greeting')->with('name', 'Sonu');

Sharing Data With All Views

We already seen how we can pass data to view, if we have to need to pass data to all the views. Then we called share function. share() method will take two argument, key and values. It is called from boot method of service provider.

Example:-

Route Path:-

Route::get('index', function(){
   return view('index');
});
Route::get('index1', function(){
   return view('index1');
});

Create two view file in views directory:-index.blade.php and index1.blade.php with same code.

   
      

AppServiceProvider- Here we have used share methed and the data that we have passed will be shared with all the views(app/Providers/AppServiceProvider.php)

Let’s look at a simple example.

share('name', 'Tutorialsplane.com');
   }

   public function register(){
      //
   }
}
Laravel Views

3. View Composers.

Views composers are callback or class method. We called this function when a view is loaded. If you have data that you want to be bound to a view each time that view is rendered. It can help you to organize that logic into a single location.

Let’s look at a simple example.


Now we have registered the composer, the ProfileComposer@compose method will be run each time at the profile view is being rendered.

Let's look at a simple example.

users = $users;
    }

    public function compose(View $view)
    {
        $view->with('count', $this->users->count());
    }
}

Attaching A Composer To Multiple Views

By using composer method we can attach muliple view at once by passing an array of views as first argument.

View::composer(
    ['profile', 'dashboard'],
    'App\Http\ViewComposers\MyViewComposer'
);

The composer method also accept the * character to allowing you to attach a composer to all views.

View::composer('*', function ($view) {
    //
});

View Creators

View creater are quite similar to view composer. They are executed immediately. To register a view creater, use the creater method.

View::creator('profile', 'App\Http\ViewCreators\ProfileCreator');

Laravel HTTP Response


Laravel HTTP Response – The Laravel HTTP Response is used to return a response. The response can be sent either from route or controller. All request has a response. The string will be automatically converted into the Http response.


Laravel HTTP Response.

Let us understand how to use laravel Http Response.

Function:-

There are some followings function available in laravel Http Response.

  • 1. Creating Response.
  • 2. Redirects.
  • 3. Other Response Types.
  • 4. Response Macros.

1. Creating Response.

Strings & Arrays

All route and controller should return a response to be sent back to the user browser. It will automatically convert string to Http response.

Route::get('response/', function () {
    return 'Hello World';
});
Laravel HTTP Response

You can also return string from route or controller to array. laravel will automatically convert the array into a json response.

Route::get('response1/', function () {
    return [1, 2, 3];
});
Laravel HTTP Response

Response Objects

You want be returning simple string or array from the route action. You will be returning full Illuminate/Http/Response instances or views.

Route::get('home', function () {
    return response('Tutorialsplane.com', 200)
       ->header('Content-Type', 'text/plain');
});
Laravel HTTP Response

Attaching Headers To Responses

We can use the header method to add a series of header to the response before sending it back to the user.

Route::get('AttachHeader', function () {
	$content = 'Soild Coupon!';
	$type = 'text/plain';
    return response($content)
            ->header('Content-Type', $type)
            ->header('X-Header-One', 'Header Value')
            ->header('X-Header-Two', 'Header Value');
});
Laravel HTTP Response

Attaching Cookies To Responses

This method allows you to easily attach cookie to the response. you can use the cookie
method to generate cookie.

Route::get('cookie', function () {
	$content = 'Tutorialsplane.com!';
	$type = 'text/plain';
	$minutes = 1;
    return response($content)
                ->header('Content-Type', $type)
                ->cookie('name', 'value', $minutes);
});
Laravel HTTP Response

Cookies & Encryption

Laravel are generated all cookie which is encrypted and signed so they can’t be modify or read by the client. If you want to disable encryption you may use $except property.

protected $except = [
    'cookie_name',
];

2. Redirects.

Redirect response are motive of the Illuminate/Http/RedirectResponse class. It is used to redirect the user to another url.

Route::get('home', function () {
    return redirect('home/dashboard');
});

Sometime user want to redirect to their previous location during the form validation. That time you may use back helper function.

Route::post('user/profile', function () {

    return back()->withInput();
});

Redirecting To named Routes

To use redirect helper with no parameter, you can use route method.

return redirect()->route('create');

You can also pass the parameter as a second argument in route method.

]

return redirect()->route('create', ['id' => 1]);

Redirecting To Controller Actions

You can also redirect to controller action. It’s a easy to do simply pass the controller and action name to the action method. You don’t need to specify full namespace to controller. it will automatically set the base controller.

return redirect()->action('HomeController@index');

if your controller route required patameter. Then you can pass second argument to the action method.

return redirect()->action(
    'UserController@profile', ['id' => 1]
);

Redirecting With Flashed Session Data

Redirecting to a new URL and flash data to the session are done. This is done after successful performing action when you give a success or failure message to the session.

Route::post('profile', function () {

    return redirect('dashboard')->with('status', 'Profile updated!');
});

After the user is redirected, you may display the flashed message on the view page like this:-

@if (session('status'))
    
{{ session('status') }}
@endif

3. Other Response Types.

The response helper is used to generate other type of response. When We called this helper without argument, contract is returned which is provide some helpful method for generating response.

View Responses

We use View method when we need to control over response status and header but also need to return on view.

return response()
            ->view('hello', $data, 200)
            ->header('Content-Type', $type);

JSON Responses

The json method will automatically set the content-type and header to application/json and convert to given array to json.

Route::get('json',function(){
   return response()->json(['name' => 'Sonu Kumar', 'state' => 'Bihar']);
});
Laravel HTTP Response

File Downloads

The download method may be used generate a response that forcly download the file at the given path. This method accept the second parameter as a file name and third is Http header.

return response()->download($pathToFile);

return response()->download($pathToFile, $name, $headers);

return response()->download($pathToFile)->deleteFileAfterSend(true);

File Responses

The file method is used to diaplay the file in the form of image or PDF. This method accept first parameter is file path and second is array of header.

return response()->file($pathToFile);

return response()->file($pathToFile, $headers);

3. Response Macros.

You want to define a custom response that you can re-use variety of your route and controller.
You can use macro method on the response facade.

Let’s look at a simple example.


The macro function accept a name as its first argument and a closure as its second.

return response()->caps('foo');

Laravel HTTP Requests


Laravel HTTP Requests – The Laravel HTTP Requests is used to retrieve the input field or any string in form of GET and POST method.


Laravel HTTP Requests.

Let us understand how to use laravel HTTP Requests.

Function:-

There are some followings function available in laravel HTTP Requests.

  • 1. Accessing The Request.
  • 2. Input Trimming & Normalization.
  • 3. Retrieving Input.
  • 4. Files.

1. Accessing The Request.

The current Http request via dependencies injection, you should type-hint Illuminate/Http/Request class on your controller method. The incoming request will automatically pushed by the service container.

Let’s look at a simple example.

input('name', 'Solid Coupon');
        echo "$name";
    }	
}

Route Path:-

Route::get('request/', 'RequestController@store');
Laravel HTTP Requests

Dependency Injection & Route Parameters

Controller method is also consider input to a route parameter uou should list your route parameter after your other dependencies.

Route::put('user/{id}', 'UserController@update');

Controller Part:-

Let’s look at a simple example.


Accessing The Request Via Route Closures

By using this method we can directly define function in route.

use Illuminate\Http\Request;

Route::get('/', function (Request $request) {
    //
});

Retrieving The Request Path, URL And Method

The Path method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which match the particular pattern of the method. The url method is used to get full url.

Example:-

First we have to create a new controller called UriController.

php artisan make:controller UriController –plain
Laravel HTTP Requests

Controller Parts:-

Let's look at a simple example.

path();
      echo 'Path Method: '.$path;
      echo '
'; $pattern = $request->is('uri/*'); echo 'is Method: '.$pattern; echo '
'; $url = $request->url(); echo 'URL method: '.$url; } }

Route Part:-

Route::get('uri/bar','UriController@index');
Laravel HTTP Requests

2. Input Trimming & Normalization.

Laravel include the TrimString and ConvertEmptyStringToNUll in global middleware stack. this middleware are listed in stack through Kernel class. It will automatically trim all incoming string field on the request and convert empty field to null.

3. Retrieving Input.

We can easily get the input value in Laravel. Doesn't matter what method was used "GET" or "POST". It will get input value for both method the same way.

EXAMPLE

Create a registration form in view directory.

Let's look at a simple example.


   
      
   

   
      
Name
Username
Password

Create a UserRegistration controller page.

php artisan make:controller UserRegistration --plain
Laravel HTTP Requests

Controller Parts:-

Let's look at a simple example.

input('name');
      echo 'Name: '.$name;
      echo '
'; $username = $request->username; echo 'Username: '.$username; echo '
'; $password = $request->password; echo 'Password: '.$password; } }

Route Part:-

Route::get('/register',function(){
   return view('register');
});
Route::post('postRegister',array('uses'=>'UserRegistration@postRegister'));
Laravel HTTP Requests

Old Input

Laravel permits you to keep input from one request to the next request. It is used for re-populating form after detecting validation errors. If you are using validation feature, you will need to use manually this method and validation facilities will call them automatically.

Flashing Input To The Session

The flash method we can use like this:-

$request->flash();

We can also use the flashOnly and flashExcept method to flash a subset of the request data to the session.

$request->flashOnly(['username', 'email']);

$request->flashExcept('password');

Flashing Input Then Redirecting

You will frequently want to flash input to the session and then redirect to the previous page.

return redirect('form')->withInput();

return redirect('form')->withInput(
    $request->except('password')
);

Retrieving Old Input

If we wnt to get flash input from the previous request. We can use old method on the request.

$username = $request->old('username');

Laravel provides a global old helper. If no old input exist for the given field, the output will be return null.


Cookies

Retrieving Cookies From Requests

Laravel framework are created all cookies which is encrypted and signed with authentication code. Means it will be considered invalid if they have been changed by the client. To get cookie value from the request we can use cookie method.

$value = $request->cookie('name');

Attaching Cookies To Responses

you can aatach cookie using the cookie method. You should pass the name, value and number of minute the cookie should be considered valid to this method.

return response('Hello World')->cookie(
    'name', 'value', $minutes
);

Generating Cookie Instances

If you would like to generate cookie. you may use global cookie helper.

$cookie = cookie('name', 'value', $minutes);

return response('Hello World')->cookie($cookie);

4. Files.

Retrieving Uploaded Files

You can access uploaded file from the Illuminate/Http/Request using the file
method. The file method return an instance of the Illuminate/Http/UploadedFile class.

$file = $request->file('photo');

$file = $request->photo;

You may determine if a file is present on the request using the hasFile method.

if ($request->hasFile('photo')) {
    //
}

Validating Successful Uploads

You can check the validation using isValid method during the uploading the file.

if ($request->file('photo')->isValid()) {
    //
}

File Paths & Extensions

It is used to access the file fully-qualified path and its extension.

$path = $request->photo->path();

$extension = $request->photo->extension();

Storing Uploaded Files

To store uploaded file we can use store method which is move an uploaded file to one of your disk.

$path = $request->photo->store('images');

$path = $request->photo->store('images', 's3');

If you don't want to file name is automatically generated. You can use the storeAs
method.

$path = $request->photo->storeAs('images', 'filename.jpg');

$path = $request->photo->storeAs('images', 'filename.jpg', 's3');

Laravel Controllers


Laravel Controllers – The Laravel Controllers is used to defined group related request handling logic into a single class and stored in the app/Http/Controllers directory.


Laravel Controllers.

Let us understand how to use laravel Controllers.

Function:-

There are some followings function available in laravel Controllers.

  • 1. Introduction.
  • 2. Basic Controllers.
  • 3. Controller Middleware.
  • 4. Resource Controllers.
  • 5. Dependency Injection & Controllers.

1. Introduction.

Insead of defining all of your request handling logic closures in route file, you may wish to organize this behavior using controller classes. Controller can group related requst handling logic into a single class. Controller are stored in the app/Http/controllers directory.

2. Basic Controllers.

Defining Controllers

In MVC framework, the letter ‘C’ stands for controller. It acts as a directing traffic between Views and Model. The controller extends the base controller class included with Laravel. The base class provides a few convenience methods such as the middleware method, which may be used to attach middleware to controller action.

EXAMPLE

First we have to create UserController using command prompt.

php artisan make:controller UserController --plain
Laravel Controllers

Controller Path:-

Let’s look at a simple example.


Define a route to this controller like this:-

Route::get('/parameter/{id}', 'UserController@parameter');
Laravel Controllers

Controllers & Namespaces

We don't need to define full controller namespace when we are defining the controller route. We only defined the specify part of the class name which is comes after the App/Http/controllers part of the namespace.

Route::get('foo', 'Photos\AdminController@method');

Single Action Controller

We want to define a controller that handles a single action, then we can use _invoke
method on the controller.

Let's look at a simple example.


When you use route for single action controller, then do not need to define method.

Route Path:-

Route::get('user/{id}', 'ShowProfile');
Laravel Controllers

3. Controller Middleware.

We can also assign the middleware to the controller route in your route file.

Route::get('profile', 'UserController@show')->middleware('auth');

By using middleware method to your controller constructor we can easily define middleware to the controller action.

Let's look at a simple example.

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware('log')->only('index');

        $this->middleware('subscribed')->except('store');
    }
}

4. Resource Controllers.

This routing is used to assign CRUD route to the controller with single line code. Like , you want to create a controller that handle all Http request for photo stored using make:controller Artsian command.

php artisan make:controller PhotoController --resource

Then it will generate controller at app/Http/controller/PhotoController.php.

Route::resource('photos', 'PhotoController');

This route declaration creates multiple route to handle a lot of action on resource.

Laravel Controllers

Spoofing Form Methods

Html form can not create PUT, PATCH or DELETE request. You need to add a hidden _method field to spoof these Http verbs. Method field helper can create this field for you.

{{ method_field('PUT') }}

Partial Resource Routes

In this we can specify the subset of action. the controller should handle the default action.

Route::resource('photo', 'PhotoController', ['only' => [
    'index', 'show'
]]);
Route::resource('photo', 'PhotoController', ['except' => [
    'create', 'store', 'update', 'destroy'
]]);

Naming Resource Routes

All controller have a route name, yet we can override these name by passing names array.

Route::resource('photo', 'PhotoController', ['names' => [
    'create' => 'photo.build'
]]);

Naming Resource Route Parameters

The Route::resource is generate the route parameter for resource route based on single version of resouce name. We can easily override by passing parameter in array.
The array should be an associative array of resource name and parameter names.

Route::resource('user', 'AdminUserController', ['parameters' => [
    'user' => 'admin_user'
]]);

Localizing Resource URIs

This method is used to create and edit action verbs. You can use Route::resourceVerbs methods. It will be generate in boot method of your AppServiceProvider.

Let's look at a simple example.

use Illuminate\Support\Facades\Route;
public function boot()
{
    Route::resourceVerbs([
        'create' => 'crear',
        'edit' => 'editar',
    ]);
}

Route path:-

Route::resource('fotos', 'PhotoController')

Supplementing Resource Controllers

If you want to add some additional route to resource controller. Tou should define before you call route::resource.

Route::get('photos/popular', 'PhotoController@method');

Route::resource('photos', 'PhotoController');

5. Dependency Injection & Controllers.

Constructor injection

The Laravel Service Container is used to resolve the controllers. You are able to type hint any dependencies your controller which need in its constructor. The dependencies will automatically be resolved and injected into the controller.

Contoller Path:-

Let's look at a simple example.

myclass = $myclass;
   }
   public function index(){
      dd($this->myclass);
   }
}

Route Path:-

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Method Injection

In this method, you can also type-hint dependencies on your controller's action methods.

Controller Path:-

Let's look at a simple example.


Route path:-

class MyClass{
   public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');

Laravel CSRF Protection


Laravel CSRF Protection – The Laravel CSRF Protection is used to make its easy to protect your application from cross site request forgery(CSRF) attack.


Laravel CSRF Protection.

Let us understand how to use laravel CSRF protection.

Function:-

There are some followings function available in laravel CSRF protection.

  • 1. Introduction.
  • 2. Excluding URIs From CSRF Protection.
  • 3. X-CSRF-TOKEN.
  • 4. X-XSRF-TOKEN.

1. Introduction.

It makes easy to protect your application from CSRF attack. Csrf are a type harmful exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF “token” for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

Anytime you define in your application, you should include a hidden CSRF token field in the form. you may use the csrf_field helper to generate the token field.

{{ csrf_field() }} ......

The VerifyCsrfToken middleware, which is included in web middleware group.

CSRF Tokens & Vue

If you are using the Vue JavaScript framework without the authentication scaffolding provided by the make::auth Artsian command. you will need to manually define a Laravel JavaScript object in your primary application layout.


2. Excluding URIs From CSRF Protection.

If you are using stripe to process payments and are utilize their webhook system. You will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

You should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file.

Let’s look at a simple example.


3. X-CSRF-TOKEN.

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header.


Then, once you have created the meta tag. you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications.

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

4. X-XSRF-TOKEN.

Laravel stores the current CSRF token in a XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set the X-XSRF-TOKEN request header.

This cookie is primarilly sent as a convenience since some javascript framework, like angular, automatically place its value in the X-XSRF-TOKEN header.

Laravel Middleware


Laravel Middleware – The Laravel Middleware is used to includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen.


Laravel Middleware.

Let us understand how to use laravel Middleware.

Function:-

There are some followings function available in laravel Middleware.

  • 1. Introduction.
  • 2. Defining Middleware.
  • 3. Registering Middleware.
  • 4. Middleware Parameters.
  • 5. Terminable Middleware.

1. Introduction.

Middleware provide a simple mechanism for filtering HTTP requests entering your application. Like Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. Still, if the user is authenticated, the middleware will allow the request to proceed further into the application.

There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/http/Middleware directory.

2. Defining Middleware.

To create a new middleware, use the make::middleware Artisan command.

php artisan make:middleware Test1Middleware

This command will place a new Test1Middleware class in your app/Http/middleware directory. In this middleware, we will only allow access to the route.

Middleware Directory Path.

Let’s look at a simple example.


The middleware can be registered at app/Http/kernel.php.

Kernel path [app/Http/kernel.php].

 protected $routeMiddleware = [
     'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
     'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
     'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
     'can' => \Illuminate\Auth\Middleware\Authorize::class,
     'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
     'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
     'test' => \App\Http\Middleware\Test1Middleware::class,
     'check' => \App\Http\Middleware\CheckAge::class,
    ];

Controller part:-


Route part:-

Route::get('test',[
   'middleware' => 'test',
   'uses' => 'MyTestController@index',
]);

Output will be like this:-

Laravel Middleware

CheckAge

Create a new middleware through command:-

php artisan make:middleware CheckAge

Middleware CheckAge Example

age <= 200) {
	echo "My age is ";
	echo $request->age;
        }
        return $next($request);
    }
}

Output will be like this:-

Laravel Middleware

Before & After Middleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application.


Output will be like this:-

Laravel Middleware

This middleware would perform its task after the request is handled by the application.


Output will be like this:-

Laravel Middleware

3. Registering Middleware.

Global Middleware

you want a middleware to run during every HTTP request to your application, simply list the middleware class in the $middleware property of your app/Http/kernel.php class.

Assigning Middleware To Routes

You would like to assign middleware to specific routes, you should first assign the middleware a key in your app/Http/kernel.php file. By default, the $routeMiddleware property of this class contains entries for the middleware included with Laravel. To add your own, simply append it to this list and assign it a key of your choosing.

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

Once the middleware has been defined in the kernel, you can use the middleware method to assign middleware to a route.

Route::get('admin/profile', function () {
    //
})->middleware('auth');

You may also assign multiple middleware to the route.

Route::get('/', function () {
    //
})->middleware('first', 'second');

When assigning middleware, you may also pass the fully qualified class name.

use App\Http\Middleware\CheckAge;
Route::get('admin/profile', function () {
    //
})->middleware(CheckAge::class);

Middleware Groups

Sometimes you may want to group several middleware under a single key to make them easier to assign to routes. You may do this using the $middlewareGroups property of your HTTP kernel.

Out of the box, Laravel comes with web and api middleware groups that contains common middleware you may want to apply to your web UI and API routes.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'auth:api',
    ],
];

Route path:-

Route::get('/', function () {
    //
})->middleware('web');

Route::group(['middleware' => ['web']], function () {
    //
});

4. Middleware Parameters.

Middleware can also receive additional parameters. For example, if your application needs to verify that the authenticated user has a given "role" before performing a given action, you could create a CheckRole middleware that receives a role name as an additional argument.

Additional middleware parameters will be passed to the middleware after the $next argument.

Middleware Parameter Example

user()->hasRole($role)) {
            // Redirect...
        }
        return $next($request);
    }
}

Route Path:-

Route::put('post/{id}', function ($id) {
    //
})->middleware('role:editor');

5. Terminable Middleware.

Sometimes a middleware may need to do some work after the HTTP response has been sent to the browser. For example, the "session" middleware included with Laravel writes the session data to storage after the response has been sent to the browser. If you define a terminate method on your middleware, it will automatically be called after the response is sent to the browser.

Middleware Terminable Example


The terminate method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of route or global middleware in the app/Http/kernel.php file.

Laravel Routing


Laravel Routing – The Laravel Routing is used to defined route in your route files, which are located in route directory .


Laravel Routing.

Let us understand how to use laravel Routing.

Function:-

There are some followings function available in laravel Routing.

  • 1. Basic Routing.
  • 2. Route Parameters.
  • 3. Named Routes.
  • 4. Route Groups.
  • 5. Route Model Binding.
  • 6. Form Method Spoofing.
  • 7. Accessing The Current Route.

1. Basic Routing.

The most basic Laravel route simply accept a uri and a closure, providing a very simple and expressive method of defining routes.

Let’s look at a simple example.


Output will be like this:-

Laravel Routing

The default route files

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

Available Router Methods

The router allows you to register routes that respond to any HTTP verb

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

Sometimes you may need to register a route that responds to multiple HTTP verbs. We can use match and any method to register a route that responds to all HTTP verbs.

Let's look at a simple example.

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

Route::any('message', function () {
    return 'Hello World';
});
Laravel Routing

CSRF Protection

Any HTML forms pointing to POST, PUT or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected.

2. Route Parameters.

Required Parameters

Sometime you will need to capture segments of the URI within your route. For example, you may need to capture a user's ID from the URL. You may do so by defining route parameters.

Route::get('/parameter/{id}', function ($id) 
{
    return 'Parameter_id_'.$id;
});
Laravel Routing

We can define as many route parameters as required by your route.

Route path (web.php):-

Route::get('/posts/{postId}/comments/{commentId}', 'AccountController@posts');

Controller part (AccountController.php):-

 Comments_id_$commentId";
   }
}
Laravel Routing

Optional Parameters

You may need to specify a route parameter, but make the presence of that route parameter optional. Make sure to give the route's corresponding variable a default value

route path:-

Route::get('user/{name?}', 'AccountController@OptionalParameter');

Controller part:-


Laravel Routing

Regular Expression Constraints

You may forcly 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 forcly.

route path:-

Route::get('expression/{id}/{name}', 'AccountController@RegularExpression')->where(['id' => '[0-9]+', 'name' => '[A-z]+']);

Controller part:-

public function RegularExpression($id, $name)
{
return "Id = $id 
Name = $name"; }
Laravel Routing

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.

public function boot()
{
    Route::pattern('id', '[0-9]+');
    parent::boot();
}

Once the pattern has been defined, then program will be executed when id is numeric.

3. Named Routes.

Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify a name for a route by chaining the name method onto the route definition.

Route::get('example/profile', function () {
    echo "Hello User!";
})->name('profile');

You can also specify route names for controller action.

Route path:-

Route::get('abc/profile', 'AccountController@nameRoute')->name('pic');

Controller path:-

public function nameRoute()
{
  return "Hello World!";		
}

Generating URLs To Named Routes

Once you have assigned a name to a given route, you may use the route's name when generating URL or redirects via the global route function.

$url = route('profile');
return redirect()->route('profile');

If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the URL in their correct positions.

Route::get('Admin/{id}/profile', function ($id) {
    $url = route('profile', ['id' => 1]);
	return "Print Always Same Result";
})->name('profile');
Laravel Routing

4. Route Groups.

Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on each individual route. Shared attributes are specified in an array format as the first parameter to the Route::group method.

Middleware

To assign middleware to all routes within a group, you may use the middleware key in the group attribute array. Middleware are executed in the order they are listed in the array.

Route::group(['middleware' => 'auth'], function () {
    Route::get('/', function ()    {
        // Uses Auth Middleware
    });

    Route::get('abc1/profile', function () {
		echo "Hii";
        // Uses Auth Middleware
    });
});

Namespaces

Another common use-case for route groups is assigning the same PHP namespace to a group of controllers using the namespace parameter in the group array.

Route::group(['namespace' => 'Admin'], function () {
    // Controllers Within The "App\Http\Controllers\Admin" Namespace
});

Sub-Domain Routing

Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route URIs, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the domain key on the group attribute array.

Route::group(['domain' => '{account}.myapp.com'], function () {
    Route::get('aa/{id}', function ($account, $id) {
        //
    });
});

Route Prefixes

The prefix group attribute may be used to prefix each route in the group with a given URI. For example, you may want to prefix all route URIs within the group with admin.

Route::group(['prefix' => 'route'], function () {
    Route::get('users', function ()    {
        return "Welcome";
    });
});
Laravel Routing

5. Route Model Binding.

When injecting a model ID to a route or controller action, you will often query to retrieve the model that corresponds to that ID. Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes. For example, instead of injecting a user's ID, you can inject the entire user model instance that matches the given ID.

Implicit Binding

Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.

Route::get('api/users/{user}', function (App\User $user) {
    return $user->email;
});

Customizing The Key Name

If you would like model binding to use a database column other than id when retrieving a given model class, you may override the getRouteKeyName method on the Eloquent model.

public function getRouteKeyName()
{
    return 'slug';
}

Explicit Binding

To register an explicit binding, use the router's model method to specify the class for a given parameter. You should define your explicit model bindings in the boot method of the RouteServiceProvider class.

public function boot()
{
    parent::boot();

    Route::model('user', App\User::class);
}

Next, define a route that contains a {user} parameter.

Route::get('profile/{user}', function (App\User $user) {
    //
});

Customizing The Resolution Logic

If you want to use your own resolution logic, you may use the Route::bind method. The closure you pass to the bind method will receive the value of the URI segment and should return the instance of the class that should be injected into the route.

public function boot()
{
    parent::boot();

    Route::bind('user', function ($value) {
        return App\User::where('name', $value)->first();
    });
}

6. Form Method Spoofing.

HTML forms do not support PUT, Patch or Delete actions. So, when defining PUT, Patch or Delete routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method ield will be used as the HTTP request method.

You can use the method_field helper to generate the _method input.

{{ method_field('PUT') }}

7. Accessing The Current Route.

You can use the current, currentRouteName and currentRouteAction methods on the route facade to access information about the route handling the incoming request.

current()->uri();
		 echo "
"; echo $actionName = Route::getCurrentRoute()->getActionName(); echo "
"; echo $routeName = $abc = Route::currentRouteName(); } }

Refer to the API documentation for both the underlying class of the route facade and Route instance to review all accessible methods.

Output will be like this:-

Laravel Routing

Laravel Contracts


Laravel Contracts – The Laravel Contracts is used to set of interfaces that define the core services provided by the framework.


Laravel Contracts.

Let us understand how to use laravel Contracts.

Function:-

There are some followings function available in laravel Contracts.

  • 1. Introduction.
  • 2. When To Use Contracts.
  • 3. How To Use Contracts.
  • 4. Contract Reference.

1. Introduction.

Laravel’s Contracts are a set of interfaces that define the core services provided by the framework. For example, a Illuminate/Contracts/Queue/Queue contract defines the methods needed for queueing jobs, while the Illuminate/Contracts/mail/Mailer contract defines the methods needed for sending e-mail.

All contract has a corresponding implementation provided by the framework. Like, Laravel provides a queue implementation with a variety of drivers, and a mailer implementation that is powered by SwiftMailer.

Laravel Contracts live in their own GitHub repository. This provides a quick reference point for all available contracts, as well as a single, decoupled package that may be utilized by package developers.

Contracts Vs. Facades

Laravel’s facades and helper functions provide a way of utilizing Laravel’s services without needing to type-hint and resolve contracts out of the service container. In most cases, each facade has an equivalent contract.

Most application will be fine regardless of whether you prefer facades or contracts. However, if you are building a package, you should strongly consider using contracts since they will be easier to test in a package context.

2. When To Use Contracts.

Contracts or facades will come down to personal taste and the tastes of your development team. Both contracts and facades can be used to create robust, well-tested Laravel applications. As long as you are keeping your class’ responsibilities focused, you will notice very few practical differences between using contracts and facades.

Loose Coupling

First, let’s review some code that is tightly coupled to a cache implementation. Consider the following.

Let’s look at a simple example.

cache = $cache;
    }   
    public function find($id)
    {
        if ($this->cache->has($id))    {
            //
        }
    }
}

In this class, the code is tightly coupled to a given cache implementation. It is tightly coupled because we are depending on a concrete Cache class from a package vendor. If the API of that package changes our code must change as well.

Instead of this approach, we can improve our code by depending on a simple, vendor agnostic interface.

Let’s look at a simple example.

cache = $cache;
    }
}

Now the code is not coupled to any specific vendor, or even Laravel. Since the contracts package contains no implementation and no dependencies, you may easily write an alternative implementation of any given contract, allowing you to replace your cache implementation without modifying any of your cache consuming code.

Simplicity

When all of Laravel’s services are neatly defined within simple interfaces, it is very easy to determine the functionality offered by a given service. The contracts serve as succinct documentation to the framework’s features.

3. How To Use Contracts.

Many types of classes in Laravel are resolved through the service container, including controller, event listeners, middleware, queued jobs and even route Closures. So, to get an implementation of a contract, you can just type-hint the interface in the constructor of the class being resolved.

Let’s look at a simple example.

redis = $redis;
    }
    public function handle(OrderWasPlaced $event)
    {
        //
    }
}

When the event listener is resolved, the service container will read the type-hints on the constructor of the class, and inject the appropriate value.

4. Contract Reference.

This table provides a quick reference to all of the Laravel contracts and their equivalent facades.

Contract Reference facade
Illuminate/Contracts/Auth/Factory Auth
Illuminate/Contracts/Auth/PasswordBroker Password
Illuminate/Contracts/Bus/Dispatcher Bus
Illuminate/Contracts/Broadcasting/Broadcaster
Illuminate/Contracts/Cache/Repository Cache
Illuminate/Contracts/Cache/Factory Cache::driver()
Illuminate/Contracts/Config/Factory Config
Illuminate/Contracts/Container/Container App
Illuminate/Contracts/Cookie/Factory Cookie
Illuminate/Contracts/Cookie/QueueingFactory Cookie::queue()
Illuminate/Contracts/Encryption/Encrypter Crypt
Illuminate/Contracts/Events/Dispatcher Event
Illuminate/Contracts/Filesystem/Cloud
Illuminate/Contracts/Filesystem/Factory File
Illuminate/Contracts/Filesystem/Filesystem File
Illuminate/Contracts/Foundation/Application App
Illuminate/Contracts/Hashing/Hasher Hash
Illuminate/Contracts/Logging/Log Log
Illuminate/Contracts/Mail/MailQueue Mail::queue()
Illuminate/Contracts/Mail/Mailer Mail
Illuminate/Contracts/Queue/Factory Queue::driver()
Illuminate/Contracts/Queue/Queue Queue
Illuminate/Contracts/Redis/Database Redis
Illuminate/Contracts/Routing/Registrar Route
Illuminate/Contracts/Routing/ResponseFactory Response
Illuminate/Contracts/Routing/UrlGenerator URL
Illuminate/Contracts/Support/Arrayable
Illuminate/Contracts/Support/Jsonable
Illuminate/Contracts/Support/Renderable
Illuminate/Contracts/Validation/Factory Validator::make()
Illuminate/Contracts/Validation/Validator
Illuminate/Contracts/View/Factory View::make()
Illuminate/Contracts/View/View