Laravel 5 Twitter OAuth using Socialite Package

By Hardik Savani | April 18, 2016 | | 3606 Viewer | Category : Laravel Twitter API


Share this post:

In Todays, Social authentication is important to implement in website because nowdays most of the users or developer etc will connected with Social network like twitter, facebook, google+, gitbub etc. So, In this post i want to share with you how to do sign in with twitter and how to do sign up with twitter. Laravel 5 provide very easy way to implement login with your twitter account and register with your twitter clent id. Laravel 5 provide us Socialite package that is help to social authentication. In this post we will make example same as like bellow preview and you can do that easily by using few following step:

Preview:

Step 1: Installation

In first step we will install Socialite Package that provide twitter api to connect with twitter. So, first open your terminal and run bellow command:

composer require laravel/socialite

After install above package we should add providers and aliases in config file, Now open config/app.php file and add service provider and aliase.

'providers' => [

....

Laravel\Socialite\SocialiteServiceProvider::class,

],

'aliases' => [

....

'Socialite' => Laravel\Socialite\Facades\Socialite::class,

],

Step 2: Create Twitter App

In this step we need twitter app id and secret that way we can get information of other user. so if you don't have twitter app account then you can create from here : Twitter App. after open this link you can see button "Create App" after click on it you see like bellow image and you can create your application:

after create account you can copy client id and secret from here :

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.php

return [

....

'twitter' => [

'client_id' => 'app id',

'client_secret' => 'add secret',

'redirect' => 'http://learnl52.hd/auth/twitter/callback',

],

]

Step 3: Create Twitter Login

In this step first we have to create migration for add twitter_id in your user table. so le's craete new migration and bellow column this way:

Migration

Schema::table('users', function ($table) {

$table->string('twitter_id');

});

After adding twitter_id column first we have to add new route for twitter login. so let's add bellow route in routes.php file.

app/Http/routes.php

Route::get('twitter', function () {

return view('twitterAuth');

});

Route::get('auth/twitter', 'Auth\AuthController@redirectToTwitter');

Route::get('auth/twitter/callback', 'Auth\AuthController@handleTwitterCallback');

After add route, we need to add method of twitter auth that method will handle twitter callback url and etc, first put bellow code on your AuthController.php file.

app/Http/Controllers/Auth/AuthController.php

namespace App\Http\Controllers\Auth;


use App\User;

use Validator;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\ThrottlesLogins;

use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use Socialite;

use Auth;

use Exception;


class AuthController extends Controller

{


use AuthenticatesAndRegistersUsers, ThrottlesLogins;


protected $redirectTo = '/';


public function __construct()

{

$this->middleware('guest', ['except' => 'logout']);

}


protected function validator(array $data)

{

return Validator::make($data, [

'name' => 'required|max:255',

'email' => 'required|email|max:255|unique:users',

'password' => 'required|confirmed|min:6',

]);

}


protected function create(array $data)

{

return User::create([

'name' => $data['name'],

'email' => $data['email'],

'password' => bcrypt($data['password']),

]);

}


public function redirectToTwitter()

{

return Socialite::driver('twitter')->redirect();

}


public function handleTwitterCallback()

{

try {

$user = Socialite::driver('twitter')->user();

$create['name'] = $user->name;

$create['email'] = $user->email;

$create['twitter_id'] = $user->id;

$userModel = new User;

$createdUser = $userModel->addNew($create);

Auth::loginUsingId($createdUser->id);

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

} catch (Exception $e) {

return redirect('auth/twitter');

}

}

}

Now add addNew() in User model, that method will check if twitter id already exists then it will return object and if not exists then create new user and return user object. so open user model and put bellow code:

app/User.php

namespace App;


use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable

{


protected $fillable = [

'name', 'email', 'password','twitter_id'

];


protected $hidden = [

'password', 'remember_token',

];


public function addNew($input)

{

$check = static::where('twitter_id',$input['twitter_id'])->first();


if(is_null($check)){

return static::create($input);

}


return $check;

}

}

Ok, now at last we need to add blade view so first create new file twitterAuth.blade.php file and put bellow code:

resources/views/twitterAuth.blade.php

@extends('layouts.app')


@section('content')

<style type="text/css">

.account-box

{

border: 2px solid rgba(153, 153, 153, 0.75);

border-radius: 2px;

-moz-border-radius: 2px;

-webkit-border-radius: 2px;

-khtml-border-radius: 2px;

-o-border-radius: 2px;

z-index: 3;

font-size: 13px !important;

font-family: "Helvetica Neue" ,Helvetica,Arial,sans-serif;

background-color: #ffffff;

padding: 20px;

}

.logo

{

background-position: 0 -4px;

margin: -5px 0 17px 80px;

position: relative;

text-align: center;

width: 138px;

}

.forgotLnk

{

margin-top: 10px;

display: block;

}

.or-box

{

position: relative;

border-top: 1px solid #dfdfdf;

padding-top: 20px;

margin-top:20px;

}

</style>

<div class="container">

<div class="row">

<div class="col-md-4 col-md-offset-4">

<div class="account-box">

<div class="logo ">

<img src="http://design.ubuntu.com/wp-content/uploads/ubuntu-logo32.png" width="80px" alt=""/>

</div>

<form class="form-signin" action="#">

<div class="form-group">

<input type="text" class="form-control" placeholder="Email" required autofocus />

</div>

<div class="form-group">

<input type="password" class="form-control" placeholder="Password" required />

</div>

<button class="btn btn-lg btn-block btn-primary" type="submit">

Sign in</button>

</form>

<a class="forgotLnk" href="http://www.jquery2dotnet.com">I can't access my account</a>

<div class="or-box">

<div class="row">

<div class="col-md-12 row-block">

<a href="{{ url('auth/twitter') }}" class="btn btn-lg btn-info btn-block">

<strong>Login With Twitter</strong>

</a>

</div>

</div>

</div>

<div class="or-box row-block">

<div class="row">

<div class="col-md-12 row-block">

<a href="http://www.jquery2dotnet.com" class="btn btn-primary btn-block">Create New Account</a>

</div>

</div>

</div>

</div>

</div>

</div>

</div>

@endsection

Ok, now you are ready to use open your browser and check here : URL + '/twitter'.



We are Recommending you: