Build Modern Laravel Apps Using Inertia.js - Ep 23, Authentication With Inertia

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
i think we can now move on to authentication and you know what i think you're going to like it because it's going to feel just like traditional authentication in laravel or in other words you're not going to deal with tokens or oauth or any of that stuff so i think you'll feel right at home so let's do this at the moment for all of these pages we've just sort of assumed that we had an authenticated user but now let's make that an actual thing so if we have a look here let's get rid of the comments we have all of this here users create a user post users settings log out really all of that should assume a logged in user so let's say route middleware we want the auth middleware and we're going to group that for all of these routes within it so i'll paste that there and reformat okay so now every single route here will inherit the auth middleware which means if i come back and i refresh the settings page we get an issue but it is actually working so it's trying to redirect me to a login route but we haven't yet created that okay let's do that now we can do it right at the top we'll say listen to a get request to login and that's going to load some new controller called login controller and a create action there but it's not quite enough you'll see right here it's trying to find a route with a name of login so not a uri but a name so let's make sure we give this a name of login so basically what's happening here is in laravel's auth middleware on the condition that you are not authenticated it tries to link you to this route with the name of login and up until this point that route didn't exist which is why we saw that error or exception okay so let's switch back and go ahead and create this controller php artisan make controller login controller all right but you know what come to think of it why don't we instead place this within an auth directory so we'll add that here and move it over and then of course i just need to update the namespace like so and then re-import that okay so we said we need a method called create and we'll say please log in just to make sure it's working okay only remaining step is to go back to our routes file and officially import it at the top all right cross your fingers come back give it a refresh and sure enough it redirects us to the login page because we're not authenticated all right let's get started now you will see that i'm using a controller here but up until this point we've been using route closures which is perfectly fine especially for small projects but yeah for most of the things i build i usually will reach for controllers across the board so maybe at some point near the end of the series i will quickly migrate all of these but yeah from now on i want to start moving toward the way i would personally construct these things okay so let's go into our login controller so let's return and we'll ask inertia to render a view called auth login and give that a reformat all right let's create that now so in my resources directory i'm going to create a new view component in the auth directory called login okay once again just to make sure it's working okay so come back we give this a refresh and there we go but now notice one thing we see the navigation bar here that really assumes you're already signed in so for example welcome back john doe and then users and settings uh we could of course conditionally display those things but really if we're logging in we probably don't need to see any of this at all so it sounds like we don't want to use the layout file in this case and you'll remember many episodes ago we automatically set the layout file just to refresh your memory here's where we require the page component and then here we say well if you didn't already set a layout let's do that for you but yeah it sounds like i want to turn that off so we may have to tweak this just a little bit let's go back to our login view and here i'm going to set layout to null okay so now if i come back to firefox oh we have an issue here even though i tried to effectively disable it it's still being applied and again that's because of the way i set this up here what we have here basically means if layout is null then just set it to this layout component so in our case layout was null so it set it to the default component okay why don't we tweak this just a little bit this is no longer quite right let's say if page.layout is undefined only on that condition do we automatically set it but if it's something else or if it's null then we should leave it alone okay now if we come back and give it a refresh i think that's gonna work yeah now we've disabled it entirely but yeah if we were to remove this it should still be applied okay that's what we want okay so let's quickly do a little bit of styling here now to save this time we already created a form in the user create page so i'm going to grab a lot of this here switch back and then we'll just tweak it a little bit but first because i disabled the layout we'll have a main section maybe an inner section here and that section would be like our white card so maybe i could say background is white maybe padding all around make it rounded something like that and we'll do swap these out here and then update this to login you know something like that so let's see what we'll need here when you're logging in you don't need to give us a name but we do need your email and your password and then we'll update this to log in and then finally down here and if we're using the options api we would do props like this or just again to keep it a little consistent we've been using the composition api so i'm going to do script setup here and then let's create our form and you'll remember we need to use a nurse's form helper and that gets imported automatically okay so what do we have here an email and a password that's what you have to give us now a little note here you'll see that i have created two script tags at the time of this recording i don't know of any way to disable the layout from within script setup that might change when you're watching this but yeah again at the moment the only way to allow for this is to create two script tags which is admittedly a little annoying just do it or stick with the options api okay so if i switch back to firefox here's what we get close but no cigar let's go back up and maybe i will put that login heading within this section and then on the form give me just a moment maybe i can put this up here let's see what that looks like switch back and getting a little closer but i would like this perfectly centered on the page so on the main section i can use standard flexbox for that flex or actually you know what why don't we do a grid and we can say place items to the center and that should achieve the same thing but for that to work we do have to make sure that this main tag takes up the full height so let's say minimum height is screen which basically means at minimum it needs to be a hundred percent of that window's height all right so if i switch back and give it a refresh yeah now it's centered okay just a couple of things and i think we're ready to go let's give it some margin bottom on the heading and then maybe we could add a border around the section yeah and maybe even increase the rounded to rounded xl and i think that's good we might want to make these borders more consistent so real quick let's get rid of all of the border gray and just stick with the default color and then on these inputs and by the way these could also be their own view components so that you don't end up with this duplication and then maybe we could we probably don't want to make them full excel but maybe a little rounded uh input might be good okay and if we switch back that's good enough for me so think about it how should we submit this form well we already have the event handler set up from the previous page so i'll scroll down and we'll declare this method and what should happen when you submit well we're already using a nurse's form helper so can i just say form dot post to login all right let's see what happens there come back give it a refresh i'll try to sign in john i don't think he exists log in and yeah now we do get a method not allowed exception we're trying to post to slash login but we haven't yet created that okay that's our next step so right up here let's listen for post to log in and that will hit a store action all right let's do that now store and this is where we log in the user all right so let's do this to save a little bit of time i'm going to go to the laravel docs and if i search for authentication in the security section of course you may know that laravel offers a bunch of starter kits or quick starts and by the way many of those will have inertia options or flavors or adapters that you can use but in our case we're just doing it manually to illustrate the basic process anyways when we manually authenticate a user here's a full example of basically what needs to happen you validate the request you try to sign in the user if that was successful you regenerate their session and then you redirect them where they intended to go otherwise you redirect back with validation errors so let's save ourselves some time and just grab all of that and paste it in here and then i will just update store and import the request and also the auth facade all right saves a little bit of time now this should be fairly easy to understand the only thing that might be confusing is redirect intended so imagine a situation where you try to visit your say settings page but you're not signed in well in that case you are trying to go to settings but it's going to redirect you to the login page well what redirect intended does is after you log in it will remember oh you were trying to go to the settings page so let's just go ahead and send you there that's how that works in our case uh we probably just want to go to the home page which would be fine but as you can see here the home page is also the default so let's get rid of it entirely and i think that'll get us going so let's go back to firefox and try to sign in again now i believe a couple episodes ago i set up a susan account but real quick just to show you that the validation is working if i log in we do see a validation error okay there we go so now we are officially signed in and do note that it redirected us to where we intended to go okay so now we can make a lot of this more dynamic before we were hard coding a user but we don't have to do that anymore so let's go into our layout and let's see welcome back username and let's see ah so we were already fetching that dynamically so it sounds like i just need to go to handle inertia requests and let's see ah yeah we must have hard-coded this a number of episodes ago now we can change this to off user name but one little thing this is gonna work so if i come back and refresh sure enough we see welcome back susan but yeah if susan is not signed in then auth user will return null and then when we try to access name on null it'll throw an error so what you might do is something like this check to see if we have an authenticated user and if so grab only the information you care about otherwise make auth equal to null and that should do it okay now before i finish up here a common question people will often ask is something like well why are you doing it like this instead of auth user and then the only method to grab only the the fields that you care about so the username or their name or their email or things like that and you can do that it's totally fine just the one thing to be aware of is that now you have a direct one-to-one relationship between your table column names and the properties that you pass to the client and you may not always want those to be the same and actually often you won't want those to be the same so that's why if we switch back to this example here we have a little more control actually in this case notice i happen to be calling it username even though it's pointing to an actual name and that's just a mistake on my part it doesn't really matter but again it's an example of how there might be situations where what you want to use on the client isn't necessarily the name of the column in the database table so with this approach we are separating the two okay but anyways if i come back to firefox and give it a refresh this is looking pretty good so now that we are logged in we need a way to log out so let's add a logout link to the navbar alright let's go to layout and let's see looks like we created a nav component settings yeah i'm just going to add another one here and this will log out now this will go to a logout endpoint and it doesn't make sense for this ever to be active so let's get rid of that and have a look refresh and yeah now we have a logout link but when i click on it of course it's going to make a get request to log out and generally it's a better practice to instead submit a post request to log a user out and luckily inertia makes this really easy so real quick notice that on our nav link component that's actually just deferring to a nurse's link component so anything i pass to navlink will be sent to the link component okay so inertia's link component includes a method prop we can use to declare the request verb or method so in our case if i wanted to make a post request it's as simple as that which is really cool usually for anything that's not a get request you'd have to create a form or do something weird like that but this should do the trick so now we haven't created that logout endpoint yet but do notice when i click on it we oh actually you know what i think a long time ago we did create a logout yeah okay i'm sorry about that okay just to show you what this would look like so if i open up the network tab we should now see that we're making a post request to log out okay so let's get rid of this entirely and i'm going to move it all the way up here if you make a post request to slash log out that will hit the login controller and maybe a destroy action but actually this is the only case where you do need to be signed in in order to access this route so i could put it within here but i just want it to be near all of the other login routes so i will manually add this on like so okay so now we'll set up our destroy action and this is very simple we can just say auth logout and then let's redirect you to the login page so i could hard code it or i could say redirect to the route named login or in real life maybe there's a splashed page for your app in which case you'd redirect there okay let's see if it works log out and it works so you see what i mean how authentication in an inertia app is really no different from how you would authenticate in a traditional laravel server side app it's the same basic process which is one of the big wins when you use inertia all of that overhead of tokens and oauth and figuring out how all of that should communicate it goes out the window you don't even need to think about it at all
Info
Channel: Laracasts
Views: 441
Rating: undefined out of 5
Keywords: web development, php, programming, laravel, laracasts, jeffrey way, coding
Id: 1xHfpDhuPzA
Channel Id: undefined
Length: 17min 0sec (1020 seconds)
Published: Wed Dec 08 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.