Laravel 5.5 Socialite for all

Create a Laravel Authentication

php artisan make:auth

Download the laravel socialite package

composer require laravel/socialite

Configuration

These credentials should be placed in your config/services.php configuration file

    'facebook' => [
        'client_id' => '337690530037',         // Your Facebook Client ID
        'client_secret' => 'f4c9f04c3344c7ef222526e2cc506', // Your Facebook Client Secret
        'redirect' => 'http://localhost:8000/login/facebook/callback',
    ], 
    'twitter' => [
        'client_id' => 'ZcY9XQU3kKJ8pktOhSgjWNJ',         // Your twitter Client ID
        'client_secret' => 'cK0m6pUZJrGjpslvgHWXVjz88q0ND7FAyEzcMi', // Your twitter Client Secret
        'redirect' => 'http://127.0.0.1:8000/login/twitter/callback',
    ],
    'google' => [
        'client_id' => '857054384681-jvq9c3bvtho429b7.apps.googleusercontent.com',   // Your google Client ID
        'client_secret' => 'MOG_QYsclYiZ11wXxqTrtn', // Your google Client Secret
        'redirect' => 'http://localhost:8000/login/google/callback',
    ],

Routing

Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. We will access Socialite using the Socialite facade:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
    
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

   /**
     * Redirect the user to the authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider($provider)
    {
        return Socialite::driver($provider)->redirect();
    }


    /**
     * Obtain the user information from authentication.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback($provider)
    {
        if ($provider == 'twitter') {
            $user = Socialite::driver('twitter')->user();
        } elseif($provider == 'facebook') {
            $user = Socialite::driver('facebook')->user();            
        }else{
            $user = Socialite::driver('google')->stateless()->user();
        }       
                
        $findUser = User::where('email', $user->email)->first();
        if ($findUser) {
            Auth::login($findUser);            
        } else {
            $newuser           = new User;
            $newuser->name     = $user->name;
            $newuser->email    = $user->email;
            $newuser->password = bcrypt(123456);
            $newuser->save();
            Auth::login($newuser);            
        }
        return redirect('home');
    }

}

Of course, you will need to define routes to your routing file routes > web.php

Route::get('login/{provider}', 'Auth\LoginController@redirectToProvider');
Route::get('login/{provider}/callback', 'Auth\LoginController@handleProviderCallback');

Edit your existing login view resources/views/auth/login.blade.php and add following HTML code.

<div class="panel-body">              
    <div class="panel-body">
        <a class="btn btn-primary" href="{{'/login/facebook'}}">
           {{'Facebook Login'}}
        </a>
        <a class="btn btn-primary" href="{{'/login/twitter'}}">
            {{'Twitter Login'}}
        </a>
        <a class="btn btn-primary" href="{{'/login/google'}}">
            {{'Google Plus'}}
        </a>
    </div>
</div>   

Laravel Socialite Facebook Login

Create a Users table

We need to run database migrations to create user table but before doing that we need to modify it to store OAuth user.

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password')->nullable(); // Set to nullable
        $table->string('token'); // OAuth Token
        $table->rememberToken();
        $table->timestamps();
    });
}

Create a Laravel Authentication

php artisan make:auth

Download the laravel socialite package

composer require laravel/socialite

Create Facebook App To Get Tokens

Go to the Facebook’s developers portal by following URL: https://developers.facebook.com/
Login via your Facebook account.

Create a new app then select facebook login product. After that, you can see the App id and App secret. You need to fill up some fields. Something like that

Configuration

Before using Socialite, you will also need to add credentials for the OAuth services your application utilizes. These credentials should be placed in your config/services.php configuration file

 'facebook' => [
        'client_id' => '3376905368878457',         // Your Facebook Client ID
        'client_secret' => 'f4c9f04c3344c7ef543222526e7874545', // Your Facebook Client Secret
        'redirect' => 'http://localhost:8000/login/facebook/callback',
    ],

Routing

Next, you are ready to authenticate users! You will need two routes: one for redirecting the user to the OAuth provider, and another for receiving the callback from the provider after authentication. We will access Socialite using the Socialite facade:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;

class LoginController extends Controller
{
 
    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Redirect the user to the facebook authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('facebook')->redirect();

    }

    /**
     * Obtain the user information from facebook.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $userSocial = Socialite::driver('facebook')->user();
        //return $userSocial->getId();
        //return $userSocial->getName();
        $findUser = User::where('email', $userSocial->email)->first();
        if ($findUser) {
            Auth::login($findUser);
            return "done with old";
        } else {
            $user           = new User;
            $user->name     = $userSocial->name;
            $user->email    = $userSocial->email;
            $user->password = bcrypt(123456);
            $user->save();
            Auth::login($user);
            return "done with new";
        }
    }
}

Of course, you will need to define routes to your controller methods:

Route::get('login/facebook', 'Auth\LoginController@redirectToProvider');
Route::get('login/facebook/callback', 'Auth\LoginController@handleProviderCallback');

Now we’ll be adding a link to our existing login form that will take the user to facebook authentication page. Edit your existing login view resources/views/auth/login.blade.php and add following HTML code.

<div class="panel-body">                         
    <div class="panel-heading">Login with Facebook</div>                            
    <div class="panel-body">
        <a class="btn btn-primary" href="{{'/login/facebook'}}">
            Facebook Login
        </a>
    </div>
</div>

Form Request Validation

Creating Form Requests

The generated class will be placed in the app/Http/Requests directory.

php artisan make:request StoreFormValidation

You can use a switch statement for multiple validations.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreFormValidation extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        /*return [
            'title' => 'required|unique:todos',
            'body' => 'required'
        ];*/

        switch ($this->method()) {
            case 'GET':
            case 'DELETE':
            {
                return [];
            }
            case 'POST':
            {
                return [
                    'title' => 'required|unique:todos|max:50',
                    'body' => 'required',
                ];
            }
            case 'PUT':
            case 'PATCH':
            {
                return [
                    'title' => 'required|max:50',
                    'body' => 'required',
                ];
            }            
            default:               
                break;
        }
    }
}

How are the validation rules evaluated?

public function store(StoreFormValidation $request)
{
    // The incoming request is valid...
}

public function update(StoreFormValidation $request, $id)
{
    // The incoming request is valid...
}

Laravel Pagination

Pagination Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class Pagination extends Controller
{
    public function paginate(){
    	// $users = User::all();
    	$users = User::paginate(8);
    	return view('pagination',compact('users'));
    }
}

Routing: routes > web.php

Route::get('list','Pagination@paginate');

pagination.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Pagination</title>
	<link rel="stylesheet" href="/css/bootstrap.css" crossorigin="anonymous">
</head>
<body>
	<div class="container">
		<div class="row">
			<div class="col-lg-6 offset-lg-3">
				<center><h2>Laravel Pagination</h2></center>
				<table class="table table-hover">
					<thead>
						<tr>
							<th scope="col">No</th>
							<th scope="col">Name</th>
							<th scope="col">Email</th>      
						</tr>
					</thead>
					<tbody>   
						@foreach ($users as $user)
							<tr>      
								<td>{{$loop->index+1}}</td>
								<td>{{$user->name}}</td>
								<td>{{$user->email}}</td>
							</tr>
						@endforeach						
					</tbody>				
				</table> 
				<div>
					{{$users->links()}}					
				</div>
			</div>
		</div>
	</div>
</body>
</html>

Customizing The Pagination View

However, the easiest way to customize the pagination views is by exporting them to your resources/views/vendor directory using the vendor:publish command:

php artisan vendor:publish --tag=laravel-pagination

This command will place the views in the resources/views/vendor/pagination directory. The default.blade.php file within this directory corresponds to the default pagination view. Edit this file to modify the pagination HTML.

Using default bootstrap

{{$users->links("pagination::bootstrap-4")}}

Database: Seeding

To create fake data inside the Database, you can use seeding. All seed classes are stored in the database/seeds directory.

To generate a seeder

php artisan make:seeder UserSeeder

Writing Factories

To get started, take a look at the database/factories/UserFactory.php file in your application.

<?php

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
        'remember_token' => str_random(10),
    ];
});

$factory->define(App\Test::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'user_id' => rand(1,100),                
    ];
});

Using Model Factories

<?php

use Illuminate\Database\Seeder;

class TestSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Test::class, 10)->create();
    }
}

<?php

use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\User::class, 10)->create();
    }
}

Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //$this->call(TestSeeder::class);
        //$this->call(UserSeeder::class);
        $this->call([
        	TestSeeder::class,
        	UserSeeder::class
        ]);       
    }
}

Running Seeders


php artisan db:seed

or 

php artisan db:seed --class=UserSeeder

Once you have written your seeder, you may need to regenerate Composer’s autoloader using the dump-autoload command:

composer dump-autoload

Middleware

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, 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.

Whenever there is request by a user then request has to go first on the middleware and when middleware authorized that request then it will go to the backend.

Defining Middleware

cd DirectoryName
php artisan make:middleware MiddlewareName

after creating middleware

<?php

namespace App\Http\Middleware;

use Closure;

class test
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ip = $request->ip();
        if($ip == '127.0.0.1'){
            throw new \Exception("your IP is correct");            
            //return redirect('/');
        }
        return $next($request);
    }
}

Assigning Middleware To Routes:

Route::get('about', function () {
    return view('about');
})->middleware('test');

Registering Middleware

If you want a middleware to run during every HTTP request to your application, you should first assign the middleware a key in your app/Http/Kernel.php file.

protected $routeMiddleware = [    
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'test' => \App\Http\Middleware\test::class,
];

Accessors & Mutators

What is accessors

Accessors also called getters are used to format data when you retrieve them from the database.

What is mutators

Mutators also called setters are used to change data before saving data inside the database.so if you want all your emails in your database to be lowercase only, you could do:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class todo extends Model
{
	/* Accessor */
	public function getNameAttribute($value){
		return ucfirst($value);
	}

	/* Mutator */
	public function setEmailAttribute($value)
	{
		$this->attributes['email'] = strtolower($value);
	}
}

Many to Many Relationship

Suppose one user has many roles.
ankur = admin,editor
salman = editor,author
You need to create 3 tables in your Database. users, roles, and role_user. After creating your table, you need to data insert

cd Directory
php artisan tinker
DB::table('users')->insert(['name'=>'Ankur','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('users')->insert(['name'=>'Salman','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'admin','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'editor','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('roles')->insert(['role'=>'author','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'1','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'2','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'2','user_id'=>'2','created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('role_user')->insert(['role_id'=>'3','user_id'=>'2','created_at'=>new DateTime,'updated_at'=>new DateTime])

Now you have to create model

cd Directory
php artisan make:model user
php artisan make:model role

User model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    public function roles()
    {
    	return $this->belongsToMany(Role::class);    
       
        /* If your table name is role_users. So You have to pass your table name as the second parameter */
        //return $this->belongsToMany(Role::class,'role_users');    
    }   
}

Role model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);

        /* If your table name is role_users. So You have to pass your table name as the second parameter */
        //return $this->belongsToMany(User::class,'role_users'); 
    }
}

Retrieve the related record:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class HomeController extends Controller
{
    public function index(){
    	$roles = user::find(2)->roles;    	
    	//$roles = user::find(2)->roles()->orderBy('role')->get();    	
    	return view('welcome',compact('roles'));
    }
}

One to One Relationship

Suppose You have a users table and passports table. Each user has only one passport number. On this case, you can one to one relationships

cd Directory
php artisan tinker
DB::table('users')->insert(['name'=>Amir,'created_at'=>new DateTime,'updated_at'=>new DateTime])
DB::table('passports')->insert(['number'=>'998787545782','user_id'=>'1','created_at'=>new DateTime,'updated_at'=>new DateTime]);

Now you have to create model for user and passport

cd Directory
php artisan make:model user
php artisan make:model passport

user model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class user extends Model
{
    public function passport(){
    	//return $this->hasOne('App\passport');
    	return $this->hasOne(Passport::class);
    }   
}

passport model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class mobile extends Model
{
    public function user(){
    	return $this->belongsTo(User::class);
    }
}

Retrieve the related record:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\user;

class HomeController extends Controller
{
    public function index(){
    	$passport_data = user::find(1)->passport;    	
    	return view('welcome',compact('passport_data'));
    }
}