LaraWoW Part 3 - Logging In The User
Damion Voshall
Software Engineer @ DiscordBrowser | Contributor to Larascord, a Laravel Discord API wrapper | PHP Laravel Full-Stack Software Solutions
Welcome back to part 3 of the WoW wrapper for Laravel. We're going to save the user's data to the db, and log them in.
Let's start by creating the migrations. Here is the User migration:
Next let's create a migration for the Access Tokens:
Perfect, now let's adjust the get method in the LarawowController.
Here we are assigning the access token to the user, this is a method that I added to the user type that sets the access_token property to the specified parameter in the method. This creates type safety to ensure the correct AccessToken type is being assigned to the user.
We added some extra error handling for some edge cases, and we're calling on a method to save the user to the database. Let's create that method in the service.
As you can see, we have a slight issue. Our User model and User type have the same name. This is why type safety is crucial. You can either import inline, or rename the import at the top of the file, I will be renaming the User type to UserType at the top of the file.
Here is the complete method for updateOrCreate. This method will check the user's access token and create the user if there isn't one in the database, otherwise, it will update the current information stored.
Don't forget to update the User model and make our new DB columns fillable.
领英推荐
Let's commit the transaction and see if it's successful
Looks like we are now successfully saving the user to the database. Next we need to save the Access Token to the database.
Let's implement this into the controller as well:
After creating a relationship between the user and the access token, we can updateOrCreate a token like this. The eloquent model will automatically fill in the foreign key constraint and will update the first token it finds.
Finally we can log in the user!
This will authenticate the user if they're not authenticated already, and then redirect them to the home route. Let's give it a try!
As you can see, on the Laravel welcome page, the login link changed to the dashboard link. Looks like we successfully logged in! Let's try displaying some information.
Nice! Our battletag is correctly displaying on the welcome page! Our OAuth functionality is nearly complete!
Thanks for checking out this article, hope it helps someone out there!