Sessions in Laravel | How to Create Sessions in Laravel | How to Use Sessions in Laravel

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up developers it's dary here and welcome back to a new video where we're going to dive into sessions and laravel i recently started using my github more and more and i was thinking about adding a repository for every video i create with a usage section at the bottom as you can see on my screen which will basically show you how the code works in text if you are interested in this let me know in the comment section down below so i can continue on creating content like this as well also don't forget to give me a follow on github whenever a user interacts with your web application data needs to be passed to another view or controller to do that the data needs to be stored temporarily and in most cases it will be done in a session the usage of a session is very important in web development because it allows you to store states between page requests so whenever you store a value from let's say the products page inside the session it can be accessed in let's say the shopping cart of your web application before we dive into using sessions we got to take a moment to talk about the configuration file of all your session settings and drivers if we navigate to the code editor you can find them like any other configuration file inside the convict folder in the root of your project directory right here if you scroll down you can see a session.php file let's open it now the first thing that you might notice right here is the driver right here which might seem odd but there are a couple drivers that you can choose from the first one is the default one which is file what this will do is store in your session inside the storage folder let me open it real quick right here the framework folder and right here you'll see a sessions folder right now it's empty but whenever you create a session it will be stored right here today's video is brought to you by cloudways a managed hosting platform for your applications cloudways has enabled businesses to scale and reach new milestones instead of worrying about server hassles with reliable 24 7 support cloudways offers complete peace of mind from surfer level nightmares furthermore its superior tools and works enhance your productivity so you can focus on creating incredible experiences with your applications it's a fast managed solution for agencies smbs and e-commerce businesses what i personally like about gladways is their slogan moving dreams forward you can also decide to store your session in a secure encrypted cookie for that you need to change file to cookie you can also store them inside a database you can store them inside a memcached a redis we got amazon web services we got dynamodb and lastly you could basically store them inside an array but for this episode we're going to use the basic file if we scroll down the list you'll see a couple more settings that we got right here lifetime is actually a pretty important one as well you can grab them from the ev file and it has a default value of 120 which stands for the amount of minutes you want to hold your session so in our case after 120 minutes so after two hours our session will be deleted now the next one which is pretty important as well is the encrypt because you can choose whether or not you want to encrypt your session data or not by default the value is false but if for some reason you're working with sensitive data you can set the value equal to true but for now let's keep it to false now like i said sessions will also be stored inside the storage folder and right here with the files you can define the storage pad which is framework for slash sessions there is some more data right here as you can see but we have covered the most important ones so i want to dive into the code and start working with our sessions in general a session allows you to save and retrieve data based on keys so let's test it out if we close over session.php file and focus on the pages controller we're going to work inside our index methods you can define a session in two ways so let me show you the first method through the session vacates right above our view let's say session right here make sure that you pull in the illuminate support vacate column colin and after the double colon we got to define a method that we want to perform in our session in our case let's start off with the put methods this method accepts two parameters the first one will be the key so let's say variable key comma it will give me an error and the second program will be the value so variable value as you might have noticed right there we are working with a key value pair so let's change it up to a value so let's remove variable key and let's set it equal to single quotes and let's call our session a name then for the value let's say john doe keep in mind that you can also add multiple names right here the only thing you need to do is to wrap your value inside a double set of brackets so let's save our session and let's navigate to a view my index method is connected to the index.blade.php view inside the views folder and right here we get to make sure that we print out our session now this can also be done with a session vacate insider view so let's say double set of current braces session column colon when you want to retrieve your values from your session you have to call the get method which accepts one parameter which will be the key that we have passed inside our put method right here so let's say in single quotes name if we save it navigate to the browser and let me open my local host and refresh it you can see that john doe which is a session that we created in the forward slash uri has been printed out as well like i said it should be accessible throughout our entire application so let's navigate back to our pages controller and right below our public function index let's create another one let's say public function about then right here we need to return a view so let's say return a view to about save it go to the web.php file because we need to create the route as well so let's duplicate it uri is forward slash about and the method that we're going to call inside the pages controller is about we obviously need to create the view so let's say about dotblade.php i'm making a lot of typos right there and what we could do right here is to go to our index page copy what we got paste it in save it navigate back to brave and let's change our end point to forward slash about and as you can see john doe is printed out again so we created a session inside our index method and we're using it inside the about page pretty cool isn't it there are a couple other methods available that you can perform on your session vacate we've already performed the two most basic ones which is the get method to get data and the put method to store values inside our session let's take an e-commerce website as an example right now you've probably seen that you can add multiple products into your shopping cart this can be done with the push method which allows you to push a value to an existing array and i think that the best possible way to showcase this is through a dd so let's go right inside our index method and let's keep our session put name which has a value of john doe i've got a question for you think about it how would you add another name inside the name key so let's say that we got a second name right now would you duplicate this line of code that we got and change the name let's try it to mary jane and right below our session let's create a dd let me hit enter right here let's say session column column get the key of name save it that's not necessary all right navigate to brave let's go to the forward slash endpoint and right here you'll see that john doe has been overridden and the value is mary jane so the second put method that we're performing right here has overwrite the first name that we got right there we got to make sure that we perform the push method rather than the put method again the push method adds a value to an array right now our first put request is a string john doe is a string so we need to wrap it around the set of brackets let's do that the value of name is equal to an array then if we replace put with push save it navigate back to brave refresh the page you'll see that the output is an array with two values index 0 is john doe and index 1 is mary jane the next method that we can perform on a session is one that i've used a couple times before on this channel and that's the has method the has method will check whether there is a value set at the provided key so if we navigate back and let's remove well we don't need to remove anything actually let's go right below our session push and let's create an if statement because inside the if statement we're going to check if our session colin collin has a key of name if it does print out so dd a piece of text of name does exist let's comment out the ddu that we have save it navigate back to brave refresh it and as you can see name does exist and if we add an else statement with another dd of name does not exist change the key insert or has method to age save it refresh it you'll see that name does not exist has been printed out we can also perform the all methods but before we do that we need to create another session while it's not necessary but let's actually do it let's remove the if statement let's delete everything after push let's create a new put method right here let's give it a key of h and the value is a set of brackets 30 35 40. if we save it and uncomment our dd we can perform the all methods so the session column column all we're going to get all values inside our session so we don't need to pass in a key and this is actually a pretty interesting method because it returns an array of everything that we got inside the session it also includes values that are set by the framework itself let's navigate back to the browser and let's refresh it and let me zoom out a little bit all right the first value that you see right here is underscore token i think that this makes sense because it's the csrf token that has been set you will also see this back whenever you submit a form from the view and you print out the entire request object now the name is equal to john doe which is the name that we created right here we got the underscore previous which has an area inside of it so if we open it you can see that the previous page that we accessed is the forward slash about page which is actually pretty cool because this is how you return back to the previous page the underscore flash has an array inside of it actually two it's called alt and new they're both empty but you can store stuff like your flash storage in here and the last array or the value that we have is h which has three values inside of it which is 30 45 and 40. now let's think about it let's imagine that h is replaced with product id and we have three different ids right here you can simply loop over your shopping cart array and print out the different ids the next two methods that we're going to perform are pretty fun to use which is the forget and the flush method what the forget method will do is removing a previously set session value let's navigate back right below our age let's say that we want to session colon colon forget it accepts one parameter which needs to be the key that you want to forget so in single quotes let's say that we want to forget the array name save it navigate back refresh it and right here you can't see name anymore like i've just mentioned we've also got the flush method which will remove all session values so if we navigate back replace forget with flush which does not accept a parameter because it will delete the entire array save it navigate back refresh it and you can see that our session is empty right now the last method is kind of a weird one and i honestly have never used it before if we navigate back and remove our flush method navigate back refresh it you'll see an underscore token which is a id that has been set by larval itself if for some reason you want to regenerate this you can perform the regenerate method let's navigate back let's say session column column regenerate save it navigate back refresh it you'll see a different token refresh it again and you'll see another one alright now that we've been over pretty much all settings that you can set for a session let's focus on a more complex example where we save our session inside the database with a user authentication change to it now before we do it let's quickly talk about the different situations on when you should be storing sessions in the database whenever you want to combine session data with metadata because you can track whenever and how often a user has logged in but you should also keep in mind that the numbers of records can grow tremendously inside your database which can make your site slow as well and that's kind of overkill right i've already got my database set up so pause the video and please do the same the first thing that we need to do is to pull in our authentication scaffolding inside the c online let's navigate to the other tab and in here let's perform composer require larval for slash ui this might take a second all right then we're going to pull in a ui so let's say php artisan ui view double dash odds it's telling us that we need to run npm install and npm run dev let's do that as you can see my webpack compiled successfully and let me actually make my terminal a little bit bigger alright so what we can do right now is to basically migrate our tables as well so let's say php artisan migrate we don't need to create the migrations ourselves for our sessions because artisan allows us to generate one with one command so let's say php artisan session column table hit enter this will create a new migration inside the database folder in the migrations folder and it's the last one right here you can see a new schema with a table name of sessions before we migrate this table as well let's just go over the things that we have right there every session has its own unique id then you can set the user id as well right here whenever a user is logged in of course but the value is nullable so it can also be zero or nothing so whenever a user is not logged in it still saves the session then we got an ip address right here and this will be the ip address that you use to access this page then we got the user underscore agent this will be the software that presents content for end users we've got the payload which is a text and the payload is basically a portion of transmitted data the last one is the last underscore activity and i think that this one speaks for itself it's just basically the last time a user had activity on your page let's put it into use inside the cli let's perform the php artisan migrate command as you can see our create underscore session underscore table has been migrated before we can actually save it inside a database we need to change up our database driver remember in the beginning of the episode where i told you that inside the convict folder we got a session.php file and let me scroll up where the session driver is equal to file instead of changing it right here let's actually close it off open the emv file and at the bottom let's create the session underscore driver environment variable and let's set it equal to database now whenever a user registers we want to make sure that we save data of a user of course i know that you can do the same thing with the authentication vacate but you can save those values inside the database so you still need to store a user inside your session so what we can do is to navigate to our registers open the odds folder open the register controller scroll down to where we create a user right here instead of returning a created user let's replace it with variable user and set it equal to this piece of code then right below we could basically say well session common column push inside the push method we're going to pass into params the first one will be the key which is the user that is logged in second one is a set of brackets hit enter then right here we're going to say well the first value that we want is the name of the user which we're going to grab from the data array that we have right here so data name and the second one is the email and which is data email you can pass in the id right here because the id has not been created it will be done inside the database so basically after this line where we return a variable user all right my session vacate hasn't been pulled in so let me do that as well save it close it off inside the pages controller let's actually remove all the session values that we have save it navigate to brave change our endpoints to forward slash register give it a name of john email us john gmail.com let's give it a password all right click on register we are logged in so we need to change our endpoints to forward slash and right here you'll see our values so our flash previous token and the login web but the most important one is the user that we store it right there so whenever a user registers we have an array right here with name and email so how does this look inside the database if i navigate to visual studio code and open a new tab perform the mysql command so i'm using a database name of use larval underscore testing then what we can say is select everything from the tables sessions this looks pretty weird let's fix this a little bit let's perform an exit let's create a new model let's quickly create a new sessions model which will grab the values from the database php aren't making me a model called session model we can't use the keyword session right here because it will be the same as the session vacate hit enter then inside the pages controller we could basically say well variable session is equal to session model pull in the app models colin colin all so give me all values now we got to make sure that we actually set the database table because right now session model does not exist so let's open our session model and let's say protect it table is single quotes sessions save it open the pages controller and let's add variable session inside the dd save it navigate to brave refresh the page and right here we have an emery let's open it and let's open this one as well we need the attributes right here and inside the attributes you'll find the id the user id the ip the user agent and the payload and the last activity which will be the day time this was it for this video where i showed you how sessions work in larval and how you can store them inside the database for now this was it for this video i hope that you enjoyed it if you actually did then please leave this video a thumbs up and if you're new to this channel please hit that subscribe button you
Info
Channel: Code With Dary
Views: 2,994
Rating: undefined out of 5
Keywords: sessions in laravel, how to use sessions in laravel, sessions, laravel session, session laravel 8, how to start a session laravel, laravel sessions code, laravel how to save session, laravel 8 session tutorial, how to use sessions in laravel php, laravel sessions with php, laravel run sessions
Id: Zap-LNZpvGA
Channel Id: undefined
Length: 22min 4sec (1324 seconds)
Published: Mon Sep 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.