Hi dev,
In this article we will show you how to create social login using facebook,google and twitter in laravle.
Social login is presently an fundamental portion of any location which performs client verification. It spares the clients a parcel of time, as they won’t ought to fill the entire shape. They fair sign up with their social account and following time they can log into the site by a single press.
The picture over appears a location that employments the social login for its sign up. In this instructional exercise, I will appear you how to include different social providers to a Laravel app utilizing Socialite a bundle built by Laravel for social authentication. Socialite right now supports verification with Facebook, Twitter, LinkedIn, Google, GitHub, and Bitbucket. For this instructional exercise, we are going include Facebook, Twitter, and Google Signups.
I’m using Laravel 8 for this article.
If you look inside database/migrations of your project, you will notice that Laravel already comes with some migrations for creating the users’ and password resets tables.
We will use the migration for creating the users’ table in this example but you can use any migration of your choice. There are a few things I want us to make changes to before creating the users’ table.
A user created via OAuth will have a provider
and we also need a provider_id
which should be unique. With Facebook, there are cases where the user does not have an email set up but a phone number and thus the hash sent back by the callback will not have an email resulting to an error. To counter this, you can set the email field to nullable but because the aim of this tutorial is to make it possible for a user to signup using any of Facebook, Twitter or Google with the same email and retain their profile, we will not make the email field nullable. Also, when creating users via OAuth we will not be passing any passwords, therefore, we need to set the password
field in the migration nullable.
Here, we are doing the following: adding provider
and provider_id
columns to the users’ table. We also make the password field in the users’ table nullable.
The up method
in your migration should look like this:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('image');
$table->string('provider');
$table->string('provider_id');
$table->string('password')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Next, on your terminal, run the migration with this command,
php artisan migrate
You need to add provider and provider_id to the list of fillable attributes in the model in our case User Model in app/User.php.
protected $fillable = [
'name', 'email', 'image', 'provider', 'provider_id', 'password',
];
We will make use of the default Laravel authentication so that we can have a boilerplate for when the user login but we would make use of the social login for authentication and not the traditional register form. To make use of the default Laravel authentication, we need to run the command below:
php artisan make:auth
To start our local server, we need to run the command php artisan serve
in our root directory, and visit the link given which in our case is http://127.0.0.1:8000
. We will notice the link for both Log in and Register has been added to the nav and users can now register and login using the traditional registration form which isn’t our focus for this tutorial.
Run the following command in the root directory of your Laravel project to add the package to your project’s dependencies:
composer require laravel/socialite
Once the installation is complete, we need to register its service provider in config/app.php.
In the providers array, of config/app.php add
Laravel\Socialite\SocialiteServiceProvider::class,
In the aliases array of the same file, add
'Socialite' => Laravel\Socialite\Facades\Socialite::class,
Now Socialite is all set up and you are ready to implement social login in your Laravel apps.
Scroll down and click on the button “Add Platform” it would show a modal and you’re to select website.
'facebook' => [
'client_id' => env('FACEBOOK_CLIENT_ID'),
'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
'redirect' => env('FACEBOOK_URL'),
],'twitter' => [
'client_id' => env('TWITTER_CLIENT_ID'),
'client_secret' => env('TWITTER_CLIENT_SECRET'),
'redirect' => env('TWITTER_URL'),
],'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_URL'),
],
FACEBOOK_CLIENT_ID=
FACEBOOK_CLIENT_SECRET=
FACEBOOK_URL=http://localhost:8000/login/facebook/callback
TWITTER_CLIENT_ID=
TWITTER_CLIENT_SECRET=
TWITTER_URL=http://127.0.0.1:8000/login/twitter/callback
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_URL=http://localhost:8000/login/google/callback
php artisan make:controller <NamofController>
e.g php artisan make:controller SocialController
use Socialite;
class SocialController extends Controller
{
public function redirect($provider)
{
return Socialite::driver($provider)->redirect();
}
}
Note: The above method handles redirect from our site to the OAuth provider.
We need to call the route in routes/web.php
Route::get('login/{provider}', 'SocialController@redirect');
Note: The above route will be used for both Facebook and Google OAuth authentication to be integrated into this tutorial.
After successful login, it will redirect to the URL we have set as our callback URL, in our case http://localhost:8000/login/facebook/callback
The route that handles the callback is shown below:
Route::get('login/{provider}/callback','SocialController@Callback');
The Callback method below will read the incoming request and retrieve the user’s information from the provider.
public function Callback($provider)
{
$userSocial = Socialite::driver($provider)->user();
}
When the callback is done, we will want to perform some functions which include: log in the user to their profile if the user exists or create a new user. To handle that, the callback method above becomes as shown below:
public function Callback($provider){
$userSocial = Socialite::driver($provider)->stateless()->user();
$users = User::where(['email' => $userSocial->getEmail()])->first();if($users){
Auth::login($users);
return redirect('/');
}else{$user = User::create([
'name' => $userSocial->getName(),
'email' => $userSocial->getEmail(),
'image' => $userSocial->getAvatar(),
'provider_id' => $userSocial->getId(),
'provider' => $provider,
]); return redirect()->route('home');
}
}
Your controller is now as shown below
use Socialite;
use Auth;
use App\User;class SocialController extends Controller
{
public function redirect($provider)
{
"Line of Code"
} public function Callback($provider)
{
"Lines of Code"
}
}
In both your registration and log in views, add this just below the closing tag of your form i.e. below the div containing the button.
resources/views/auth/register.blade.php and resources/views/auth/login.blade.php
<form>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<a href="{{ url('/login/facebook') }}" class="btn btn-facebook"> Facebook</a>
</div>
</div>
</form>
Check the home.blade.php view and add the following:
<p>My name: {{Auth::user()->name}}</p>
<p>My Email: {{Auth::user()->email}}</p>
<img alt="{{Auth::user()->name}}" src="{{Auth::user()->image}}"/>
The Auth Facade would return the currently logged in user’s name, email and image respectively.
After successful login, you would see your name, email, and avatar on the homepage.
We Have Successfully Implemented Facebook login to our Laravel app using Socialite.
Note: Twitter doesn’t make use of localhost. For more information about that, you can check this link. Also, you’ll need to add your phone number to be able to create an app in twitter. Visit the link to add a phone number to your account if you don’t already.
We need to create a callback method in the controller created earlier on for Twitter because the AbstractProvider
for the TwitterProvider
does not implement stateless()
. i.e. stateless OAuth is not possible with the TwitterProvider in the Laravel Socialite package out of the box.
public function TwitterCallback()
{
$twitterSocial = Socialite::driver('twitter')->user();
$users = User::where(['email' => $twitterSocial->getEmail()])->first();if($users){
Auth::login($users);
return redirect('/home');
}
else{
$user = User::firstOrCreate([
'name' => $twitterSocial->getName(),
'email' => $twitterSocial->getEmail(),
'image' => $twitterSocial->getAvatar(),
'provider_id' => $twitterSocial->getId(),
'provider' => 'twitter',
]);
return redirect()->route('home');
}
}
The method above handles the callback for twitter only.
Call the method on your routes as shown below:
Route::get('login/twitter/callback', 'SocialController@TwitterCallback');
Now I would add a link to resources/views/auth/login.blade.php & resources/views/auth/register.blade.php.
<a href="{{ url('/login/twitter') }}" class="btn btn-twitter"> Twitter</a>
Note: The routes and controller have already been done earlier on.
At login using Twitter, the user is redirected to the page shown below if he is logged in to Twitter on the browser else to another page.
When we authorize the app, it would create the user if the email is not registered then it redirects to the home page with the details of the user or just redirects to the homepage for a register email address.
We Have Successfully Implemented Twitter login to our Laravel app using Socialite.
After the app is created, the redirects to the dashboard where we’re to Enable Apis and Services by following the link.
You’ve successfully enabled Google+ API to your app, and it will redirect to another page but click on Credentials on the left side of navigation and select OAuth consent screen tab and fill out the details here.
Now we need to create credentials for your app. Click credentials in left side navigation and select Credentials. In the drop-down select OAuth client ID.
Now we would add a link to resources/views/auth/login.blade.php & resources/views/auth/register.blade.php.
<a href="{{ url('/login/google') }}" class="btn btn-google-plus"> Google</a>
Note: The routes and controller have already been done earlier on.
If not logged in, we would be redirected to the page above.
When we authorize the app, it would create the user if the email is not registered then it redirects to the home page with the details of the user or just redirects to the home page for a registered email address.
We Have Successfully Implemented Google + login to our Laravel app using Socialite.
We have successfully implemented social login in Facebook, Twitter, and Google using Socialite — The official package provided by Laravel for OAuth authentication.
Hope it can help you…
Categories : Laravel
Tags : Laravel Packages Socialite
order fenofibrate 160mg online fenofibrate 160mg drug buy fenofibrate 160mg without prescription
generic cialis india sildenafil for men buy viagra 50mg pills
pill zaditor 1 mg purchase tofranil sale buy tofranil 25mg pills
precose drug precose 50mg sale fulvicin 250 mg price
purchase aspirin pill purchase hydroquinone online cheap buy imiquad sale
cheap dipyridamole 25mg dipyridamole 100mg without prescription pravachol 20mg over the counter
order meloset 3mg online how to buy meloset danocrine cost
buy dydrogesterone pills for sale purchase empagliflozin generic order empagliflozin
pill florinef 100mcg cheap bisacodyl 5mg loperamide 2mg pills
buy prasugrel pills for sale generic prasugrel 10 mg cheap tolterodine 2mg
buy ferrous sulfate 100 mg without prescription ascorbic acid 500 mg canada generic betapace 40 mg
order pyridostigmine 60mg sale order mestinon 60 mg rizatriptan 5mg cheap
order enalapril 10mg without prescription purchase bicalutamide online cheap duphalac price
buy latanoprost eye drop for sale exelon ca buy rivastigmine 3mg generic
order premarin 600 mg dostinex 0.5mg tablet sildenafil 100mg canada
how to get omeprazole without a prescription singulair over the counter buy metoprolol no prescription
telmisartan without prescription brand molnunat 200 mg buy molnupiravir 200 mg generic
purchase cialis online sildenafil 100mg cheap guaranteed viagra overnight delivery usa
oral cenforce 100mg order aralen 250mg chloroquine generic
modafinil 200mg tablet order prednisone 10mg sale order deltasone online
buy cefdinir 300mg omnicef brand lansoprazole 15mg for sale
isotretinoin 10mg price generic accutane 10mg azithromycin without prescription
azipro 250mg oral azithromycin 500mg pills cheap neurontin without prescription
order generic atorvastatin 10mg proventil 100 mcg generic norvasc 10mg brand
spins real money slot online lasix 40mg over the counter
generic protonix 20mg buy generic protonix over the counter pyridium 200mg canada
casino game oral acticlate brand albuterol
free roulette purchase stromectol generic ivermectin 0.5%
amantadine generic buy dapsone no prescription purchase avlosulfon pill
casino world free casino slot games order levoxyl sale
cost clomiphene 50mg isosorbide usa how to get imuran without a prescription
medrol 4mg tablets buy nifedipine 10mg buy generic triamcinolone online
buy vardenafil pills buy zanaflex cheap tizanidine 2mg over the counter
buy perindopril 8mg for sale allegra brand fexofenadine sale
phenytoin us buy flexeril cheap ditropan online order
buy lioresal online cheap buy lioresal sale toradol generic
buy claritin paypal loratadine 10mg cost cheap priligy 90mg
baclofen pill ketorolac for sale buy generic ketorolac online
order fosamax 70mg without prescription colchicine 0.5mg tablet macrodantin oral
inderal cost order inderal 20mg buy cheap plavix
order nortriptyline 25mg order anacin online oral paracetamol 500mg
order glimepiride 4mg for sale etoricoxib 120mg tablet etoricoxib order
medex pills buy paroxetine 20mg online buy maxolon paypal
orlistat 60mg generic cheap orlistat 120mg diltiazem sale
pepcid 40mg sale buy famotidine 20mg online cheap order prograf for sale
buy astelin medication buy avapro 300mg online cheap buy avapro pill
order esomeprazole 20mg online cheap order topiramate 200mg generic order generic topamax 200mg
imitrex where to buy avodart 0.5mg for sale avodart canada
zyloprim 100mg over the counter buy generic zyloprim rosuvastatin without prescription
zantac 300mg usa order zantac 150mg for sale buy celebrex 200mg generic
buspirone 10mg canada buy zetia 10mg online cheap cordarone 100mg pill
buy flomax 0.2mg generic ondansetron 8mg tablet order simvastatin 10mg for sale
buy domperidone online cheap order domperidone 10mg for sale sumycin 250mg over the counter
spironolactone cheap oral valtrex 500mg finasteride oral
essays for sale online cheap custom essay write my essay help
order diflucan generic ampicillin sale cipro 500mg for sale
buy sildenafil 50mg pill estradiol 2mg tablet buy estradiol 1mg for sale
flagyl online buy metronidazole 200mg pill keflex 500mg without prescription
lamotrigine 50mg pills lamotrigine uk nemazole order
cleocin 150mg us hims ed pills buy erectile dysfunction meds
retin gel price buy tadalis without a prescription purchase avana for sale
order nolvadex 20mg sale budesonide inhalers cheap rhinocort
order tadalafil pills order tadalafil 10mg purchase indocin online cheap
order cefuroxime 500mg purchase robaxin generic order generic methocarbamol 500mg
order desyrel 50mg pills trazodone 100mg canada where can i buy clindamycin
buy terbinafine without prescription gamble online with real money best casino slot games
aspirin ca casino play online casino real money us
write my essay help college essay b order generic suprax 200mg
online thesis writing best online casinos real money play poker online for real money
FKuuriUSSijhxuloAyR
order trimox 250mg generic order amoxicillin 500mg online biaxin 500mg cost
purchase calcitriol generic buy calcitriol 0.25mg online fenofibrate 160mg over the counter
buy clonidine 0.1 mg order tiotropium bromide 9 mcg buy spiriva no prescription
strong acne medication prescription prescription acne medication names trileptal 300mg canada
order alfuzosin 10 mg pill best allergy pills for adults abdominal pain over the counter
minocycline 50mg without prescription order terazosin pills buy generic requip
online doctors that prescribe ambien jak inhibitor approved for alopecia get weight loss prescriptions online
order letrozole 2.5mg generic order abilify pills order abilify pills
IBjTfUMEWlHPSwyeicClfxpzH
free nhs stop smoking service list of dmard how do pain killers work
cheap provera buy provera generic order microzide 25 mg online cheap
buy medication for herpes online type 2 diabetes pills names anti diabetic pills
buy cyproheptadine 4 mg order ketoconazole 200 mg pills purchase ketoconazole
best supplements for fungal infections blood pressure medications name brands antihypertensive drug classification chart
order duloxetine 40mg pill provigil 200mg pill buy modafinil 200mg pill
gastric erosion meaning best online doctors for uti gram positive bacilli in urine
buy promethazine 25mg sale buy ed pills medication ivermectin price canada
birth control refill online buy emergency contraception online best ejaculation delay pills
buy prednisone 10mg without prescription where can i buy amoxil amoxicillin 1000mg without prescription
safest daily antacid pills to reduce flatulence prescription for gas and bloating
order zithromax for sale order zithromax 250mg online cheap gabapentin 100mg cost
cheap urso order zyrtec 5mg sale how to buy zyrtec
Elyse Holmes
how to get atomoxetine without a prescription strattera 10mg usa purchase sertraline for sale
Kamari Hodge
buy furosemide pill diuretic buy furosemide 40mg online cheap buy albuterol generic
how to get escitalopram without a prescription order escitalopram 10mg online buy naltrexone 50 mg sale
buy generic ipratropium order ipratropium 100 mcg online cheap buy linezolid pill
buy augmentin 1000mg for sale synthroid online buy order clomiphene generic
starlix 120 mg pills candesartan order order atacand 16mg online cheap
levitra 10mg price order tizanidine 2mg pills purchase plaquenil online
carbamazepine 400mg over the counter carbamazepine 400mg usa buy lincocin 500mg
order cenforce 100mg generic order cenforce 50mg for sale glucophage over the counter
duricef 250mg usa buy epivir cheap buy epivir paypal
buy lipitor 20mg generic buy amlodipine 5mg for sale buy zestril 10mg generic
order dostinex online order loratadine sale priligy pills
medrol 4mg over counter buy methylprednisolone medication desloratadine sale
order misoprostol 200mcg for sale purchase cytotec sale buy cheap generic diltiazem
nootropil 800 mg cheap buy betamethasone generic purchase clomipramine generic
buy acyclovir 400mg online cheap order acyclovir 400mg rosuvastatin 20mg over the counter
itraconazole sale oral tinidazole 500mg how to buy tinidazole
order zetia for sale sumycin 250mg sale buy sumycin 250mg for sale
zyprexa 10mg without prescription diovan 160mg cheap diovan 80mg cheap
order cyclobenzaprine 15mg generic flexeril 15mg without prescription toradol 10mg ca
Jade Ramos
purchase colchicine online inderal 10mg oral buy methotrexate without a prescription
medication to clear acne acne medication pills from dermatologist benzoyl peroxide prescription strength lists
major brand allergy pills medrol price allergy pills for adults
best medicine for nausea over the counter best prescription drug for nausea
sleeping tablets prescribed by doctors buy meloset 3mg for sale
prednisone buy online prednisone 20mg cheap
best medicine for stomach problems buy bactrim generic
medication for persistent adult acne order deltasone without prescription salicylic acid versus benzoyl peroxide
best non prescription allergy medication order triamcinolone sale can flonase make you sleepy
alternative painkiller to co codamol glimepiride generic
Решил признаться в чувствах и подарил ей прекрасный букет от "Цветов.ру". Эти цветы стали моими немыми словами любви. Рекомендую всем, кто хочет сделать важное признание – выбирайте "Цветов.ру" для ваших эмоциональных шедевров. Советую! Вот ссылка https://fm-upgrade.ru/vrn/ - заказ цветов
buy accutane 40mg sale buy accutane medication buy isotretinoin tablets
Nelson Bradley
purchase amoxicillin online cheap order amoxicillin 500mg pills cheap amoxicillin tablets
super strong sleeping pills buy generic meloset for sale
buy azithromycin 250mg pill zithromax drug zithromax cost
buy neurontin medication order neurontin 600mg sale
azithromycin for sale order azipro generic azithromycin price
order generic lasix oral lasix
buy omnacortil 20mg for sale order prednisolone 40mg sale order omnacortil 5mg for sale
amoxicillin tablets buy generic amoxil 250mg purchase amoxicillin without prescription
order generic monodox buy monodox sale
Aurelia Burnett
generic ventolin 2mg order albuterol online cheap buy ventolin inhalator generic
brand augmentin 375mg purchase amoxiclav generic
order synthroid 100mcg generic levoxyl canada cheap levothyroxine generic
levitra sale purchase levitra sale
Esmeralda Hayden
buy generic clomiphene for sale clomid 100mg cost cost clomiphene
Мой переход к здоровому питанию был упрощён благодаря решению соковыжималки шнековые купить от 'Все соки'. Они предлагают отличное качество и удобство в использовании. С их помощью я теперь готовлю вкусные и полезные соки каждое утро. https://blender-bs5.ru/collection/shnekovye-sokovyzhimalki - Соковыжималки шнековые купить - это было важно для моего здоровья.
brand zanaflex tizanidine pills tizanidine drug
rybelsus 14mg without prescription order rybelsus 14mg order rybelsus 14 mg
prednisone ca buy generic deltasone 5mg prednisone 5mg cost
order accutane 20mg sale buy absorica generic buy generic isotretinoin over the counter
amoxicillin 1000mg ca order generic amoxicillin 500mg amoxil online order
buy albuterol paypal buy generic ventolin 4mg ventolin over the counter
buy azithromycin 500mg pill buy azithromycin online oral azithromycin
amoxiclav buy online purchase augmentin online amoxiclav us
prednisolone 20mg cheap omnacortil online order buy generic omnacortil over the counter
semaglutide 14mg cheap purchase rybelsus pills cost semaglutide 14 mg
online blackjack gambling best real casino online hard rock casino online
buy vardenafil pills order generic vardenafil brand levitra 10mg
buy pregabalin 150mg for sale cheap lyrica 150mg pregabalin 150mg ca
plaquenil 200mg generic order generic hydroxychloroquine 400mg buy generic plaquenil 200mg
aristocort ca triamcinolone 10mg cost triamcinolone generic
order tadalafil 10mg without prescription cheap tadalafil pills cialis 5mg ca
desloratadine price how to buy desloratadine buy desloratadine online
cenforce pills buy cenforce for sale cenforce online
loratadine 10mg without prescription claritin online buy order claritin 10mg pills
xenical price buy diltiazem without a prescription buy generic diltiazem online
order glycomet generic brand metformin 500mg buy glycomet 500mg online cheap
order zovirax 400mg brand zovirax 400mg order generic zyloprim 300mg
amlodipine 10mg ca amlodipine us cheap norvasc 10mg
rosuvastatin pills buy rosuvastatin pills for sale buy ezetimibe 10mg pills
buy prinivil lisinopril 10mg generic zestril 5mg tablet
buy cheap generic domperidone buy tetracycline 250mg pills order sumycin for sale
prilosec tablet order prilosec 10mg for sale buy generic prilosec for sale
cyclobenzaprine 15mg us purchase ozobax pill where to buy ozobax without a prescription
buy metoprolol pill brand lopressor buy metoprolol pill
order toradol 10mg online gloperba oral order colcrys 0.5mg generic
buy atenolol 100mg sale buy tenormin 100mg without prescription atenolol for sale online
jaemie jeskey
keadra bennetsen
Jamie Andersen