Login with Twitter in Laravel 9 Using Laravel Socialite
We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you. free coder
Today what you are going to learn:
In past, I have published an article on Login with Twitter in PHP. One of our readers asked to write an article on login with Twitter in Laravel. Though Laravel is built on the top of PHP programming language I know that mentioned tutorial is not suitable for the Laravel framework. Laravel has its own standards, folder structure, and development flow. A developer should follow the standards of Laravel while building web applications in it.
Laravel releases a few official packages that help developers achieve certain functionality. One of the packages is Socialite. Using Laravel Socialite, one can integrate social login with different providers like Facebook, Twitter, LinkedIn, Google, etc. The focus of this tutorial is on Twitter and thus in this article, we study Login with Twitter in Laravel using Socialite.
Let’s start with the fresh Laravel installation. It’s not compulsory to use a new Laravel installation, you can also use your existing project.
For installing fresh Laravel, run the command below:
Upon installation, create the database and add its credentials to the .env file. We are building a login system, so we need to store user details in the database.
When a user logged in with Twitter, we will get their unique Twitter id. To store this id I’ll add the columns provider and provider_id to the ‘users’ table. The column provider will store the value as ‘twitter’ and a column provider_id is for the user’s Twitter id.
As the user is using a social website for login, we don’t need a password. Our ‘password’ column should accept the ‘NULL’ value as default. Also, there is no guarantee of getting the user’s email so the ’email’ column would also accept the ‘NULL’ value.
Open the ‘users’ table migration file and add the code below.
Make sure to replace the placeholders with actual API keys. Finally in the LoginController, I am writing a few methods that redirect a user to Twitter for login, and on successful authentication, it will store the user’s information and log the user in.
redirectToProvider() : Inititates a OAuth flow and responsible to redirect users on login page of Twitter.
handleProviderCallback() : When user come back to application after login, get the user details and log the user in.
findOrCreateUser() : Insert the user entries to the database.
* Where to redirect users after login.
* @var string
* Call the view
* Redirect the user to the Twitter authentication page.