Friday 29 January 2016

Log every request & response in Laravel 5.1

Hi Everybody,

Today we will discuss about how to log every request & response in Laravel 5.1.

Sometimes it's useful to log some/all requests to your application. This is really convenient when you use Laravel to build your APIs.

A logging middleware might log all incoming requests to your application. In Laravel 5.1 there is a terminate method and it's call after the sending HTTP response to the browser. This way we have access to both $request and $response at the same time.

Let's take a look at how we are going to achieve this in Laravel 5.1:

Create a new middleware by type this command in terminal inside your project directory.
php artisan make:middleware LogAfterRequest
And then put below code in it(project_dir/app/Http/Middleware/LogAfterRequest.php).

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogAfterRequest {

    public function handle($request, Closure $next)
    {
        return $next($request);
    }

    public function terminate($request, $response)
    {
        Log::info('app.requests', ['request' => $request->all(), 'response' => $response]);
    }

}

In this code terminate method receives $request and $response. These are objects which will give you all of the handy stuffs you probably need to log.

When we have our middleware ready, we should add it to our HTTP Kernel.

Open Kernel.php and add this line to your protected $middleware property:

\App\Http\Middleware\LogAfterRequest::class

That's it. You can additionally filter what you want to actually log, but this is the basics.

Thanks.


Friday 22 January 2016

Email verification at the time of signup a user with Laravel 5.1

Hi Everybody,

There are a number of situations in which it is beneficial to get a newly registered user of your site to verify their email address. We will talk about when you should include this functionality and then implement email verification within a Laravel app.


User Table Migration

We need to create just two fields in addition to the fields that are standard in most users tables (username, email, password, etc.). Firstly, we need a boolean field 'confirmed' to keep track of whether a user has confirmed their email address, this will be set to false by default.

The second field that we require is a confirmation_code string field. When a user is signed up we set this field to a random string, an email is then sent to the user asking them to confirm their account by following a link to /register/verify. When a user follows this link, we take the passed in confirmation code and search for it within the users table. If a matching confirmation code is found we set the confirmed field for this user to true and set the confirmation code to null.

The migration below is for a very basic user table. Notice that the confirmed field is set to false by default and that the confirmation_code is nullable.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateUsersTable extends Migration {

    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('password');
            $table->boolean('confirmed')->default(0);
            $table->string('confirmation_code')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('users');
    }
}

Registering A User

After validation, we need to create the user, just remember that if you are use mass assignment with User::create(), you need to set the $fillable property on your user model to contain username, email, password and confirmation code.

Once the user has been created the only thing left to do is to send them their confirmation email. As stated earlier the convention that we are going to follow for the confirmation route is /register/verify/{confirmation_code}. We will use Laravel's Mail::send() and create a very basic email template that will take the confirmation code and output a link to the confirmation url that the user needs to visit.

<?php

use Illuminate\Support\Facades\Input;

use Illuminate\Support\Facades\Session;
use App\Http\Requests;

class RegistrationController extends \BaseController {

    public function store(Request $request)
    {
        $rules = [
            'username' => 'required|min:6|unique:users',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:6'
        ];

        $input = Input::only(
            'username',
            'email',
            'password',
            'password_confirmation'
        );

        $validator = Validator::make($input, $rules);

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        $confirmation_code = str_random(30);

        User::create([
            'username' => Input::get('username'),
            'email' => Input::get('email'),
            'password' => Hash::make(Input::get('password')),
            'confirmation_code' => $confirmation_code
        ]);

        Mail::send('email.verify', $confirmation_code, function($message) {
            $message->to(Input::get('email'), Input::get('username'))
                ->subject('Verify your email address');
        });

       $request->session()->flash('status', 'Thanks for signing up! Please check your email.');
       return redirect()->intended("login");
    }
}

and the simple verification email using blade:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <h2>Verify Your Email Address</h2>

        <div>
            Thanks for creating an account with the verification demo app.
            Please follow the link below to verify your email address
            {{ URL::to('register/verify/?confirm_code=' . $confirmation_code) }}.<br/>

        </div>

    </body>
</html>

Confirming The User

To complete the confirmation process the user must follow the link that is sent to them in their welcome email. A corresponding entry should be included in the routes.php file:

Route::get('register/verify', [
    'as' => 'confirmation_path',
    'uses' => 'RegistrationController@confirm'
]);

<?php
use Illuminate\Support\Facades\Session;
use App\Http\Requests;
class RegistrationController extends \BaseController {

    public function confirm(Requests $request)
    {
         $data = $request->all();
        $confirmation_code = $data['confirm_code'] ;
        if( ! $confirmation_code)
        {
          $request->session()->flash('status', 'Invalid link.');
          return redirect()->intended("login");
        }

        $user = User::whereConfirmationCode($confirmation_code)->first();

        if ( ! $user)
        {
          $request->session()->flash('status', 'Invalid link.');
          return redirect()->intended("login");
        }

        $user->confirmed = 1;
        $user->confirmation_code = null;
        $user->save();
        $request->session()->flash('status', 'You have successfully verified your account.');
        return redirect()->intended("home");
    }
}

Logging A User In

The only addition that needs to be made to the authentication system is to check whether the user is confirmed prior to logging in. Laravel's Auth::attempt() function can take extra conditions which must be true for a successful login attempt. This means we can add 'confirmed' => 1 to our credentials array to ensure that a user is confirmed before they can log in.

<?php
use Illuminate\Support\Facades\Session;
use App\Http\Requests;

class SessionsController extends \BaseController {

    public function store(Requests $request)
    {
        $rules = [
            'username' => 'required|exists:users',
            'password' => 'required'
        ];

        $input = Input::only('username', 'email', 'password');

        $validator = Validator::make($input, $rules);

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        $credentials = [
            'username' => Input::get('username'),
            'password' => Input::get('password'),
            'confirmed' => 1
        ];

        if ( ! Auth::attempt($credentials))
        {
             $request->session()->flash('status', 'We were unable to sign you in.');
            return redirect()->intended("login");
        }

        $request->session()->flash('status', 'Welcome Back.');
        return redirect()->intended("home");
    }
}

Note:-In above code we have used session to display message in view(in login and home view).
So we need below code in both views

@if(Session::has('status'))
    <div class="alert alert-success"><span class="glyphicon glyphicon-ok"></span><em> {!! session('status') !!}</em></div>
@endif

If you have any questions then please leave a comment below and I will do my best to help out.

Friday 15 January 2016

How to implement authentication for web application in Laravel 5.2

Hi Everybody,

Today we will discuss how to implement authentication for web application in Laravel 5.2

Many of the applications you build in Laravel have a similar Saas-type framework: user signup, user login, password reset, public sales page, logged-in dashboard, logout route, and a base Bootstrap style for when you're just getting started.

Now all resource related to login, register and home page generate by one command(given below) in Laravel 5.2

php artisan make:auth

Command line output of artisan make:auth




What does it provide? Let's dig in.

What changed(from Laravel 5.1 to Laravel 5.2)

We have a layout (resources/views/layouts/app.blade.php) that is the core of this scaffold, and then a series of views that extend it:

welcome.blade.php - the public welcome page
home.blade.php - the dashboard for logged-in users
auth/login.blade.php - the login page
auth/register.blade.php - the register/signup page
auth/passwords/email.blade.php - the password reset confirmation page
auth/passwords/reset.blade.php - the password reset prompt page
auth/emails/password.blade.php - the password reset email

Our public page is still routed via routes.php:

Route::get('/', function () {
    return view('welcome');
});
And we now have a HomeController, which routes our dashboard:

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return Response
     */
    public function index()
    {
        return view('home');
    }
}

This is of course routed in routes.php in the web group. And notice that there's something else new there: The Route::auth() method:

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

    Route::get('/home', 'HomeController@index');
});


Route::auth()

The auth() method is a shortcut to defining the following routes:

// Authentication Routes...
$this->get('login', 'Auth\AuthController@showLoginForm');
$this->post('login', 'Auth\AuthController@login');
$this->get('logout', 'Auth\AuthController@logout');

// Registration Routes...
$this->get('register', 'Auth\AuthController@showRegistrationForm');
$this->post('register', 'Auth\AuthController@register');

// Password Reset Routes...
$this->get('password/reset/{token?}', 'Auth\PasswordController@showResetForm');
$this->post('password/email', 'Auth\PasswordController@sendResetLinkEmail');
$this->post('password/reset', 'Auth\PasswordController@reset');


The frontend

Now let's take a look at what we get in the browser:

Screenshot of the output from a default auth scaffold view



As you can see we have Bootstrap CSS, a basic Bootstrap app layout, and helpful to our basic auth actions.

App.blade.php 

So what does this master layout look like?

We get FontAwesome, the Lato font, Bootstrap CSS, a basic hamburger-on-mobile responsive layout, jQuery, Bootstrap JS, and placeholders that are commented out for the default output CSS and JS files if you choose to use Elixir.

We also have a top nav that links us home, and links guests to either login or register, and links authenticated users to log out.

Conclusion 

That's it! It's not anything complex, but it's 30-60 minutes of typing that you just saved on every app that needs it.

Friday 8 January 2016

How to implement Breadcrumbs in Laravel 5.1

Hi Everybody

First of all happy new year!!!!

Today we will discuss about how to implement Breadcrumbs in Laravel 5.1.

1. Install Laravel Breadcrumbs


Note:-Laravel 5.0 or above is required – use the 2.x version for Laravel 4.

Install with Composer

Run this at the command line:

$ composer require davejamesmiller/laravel-breadcrumbs

This will both update composer.json and install the package into the vendor/ directory.
Add to config/app.php

Add the service provider to providers:

'providers' => [
    // ...
    DaveJamesMiller\Breadcrumbs\ServiceProvider::class,
],

And add the facade to aliases:

'aliases' => [
    // ...
    'Breadcrumbs' => DaveJamesMiller\Breadcrumbs\Facade::class,
],

2. Define your breadcrumbs


Create a file called app/Http/breadcrumbs.php that looks like this:

<?php

// Home
Breadcrumbs::register('home', function($breadcrumbs)
{
    $breadcrumbs->push('Home', route('home'));
});

// Home > About
Breadcrumbs::register('about', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('About', route('about'));
});

// Home > Blog
Breadcrumbs::register('blog', function($breadcrumbs)
{
    $breadcrumbs->parent('home');
    $breadcrumbs->push('Blog', route('blog'));
});

// Home > Blog > [Category]
Breadcrumbs::register('category', function($breadcrumbs, $category)
{
    $breadcrumbs->parent('blog');
    $breadcrumbs->push($category->title, route('category', $category->id));
});

// Home > Blog > [Category] > [Page]
Breadcrumbs::register('page', function($breadcrumbs, $page)
{
    $breadcrumbs->parent('category', $page->category);
    $breadcrumbs->push($page->title, route('page', $page->id));
});

3. Choose a template


By default a Bootstrap-compatible ordered list will be rendered, so if you’re using Bootstrap 3 you can skip this step.

First initialise the config file by running this command:

$ php artisan vendor:publish

Then open config/breadcrumbs.php and edit this line:

'view' => 'breadcrumbs::bootstrap3',

The possible values are:

    Bootstrap 3: breadcrumbs::bootstrap3
    Bootstrap 2: breadcrumbs::bootstrap2
    The path to a custom view: e.g. _partials/breadcrumbs

4. Output the breadcrumbs


Finally, call Breadcrumbs::render() in the view template for each page, passing it the name of the breadcrumb to use and any additional parameters – for example:

{!! Breadcrumbs::render('home') !!}

{!! Breadcrumbs::render('category', $category) !!}

Thanks.