Cache in Laravel | How to Create Cache in Laravel | How to Use Cache in Laravel

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up developer says dory here and welcome back to a new video where we're going to dive into cash 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 which will basically show you how to code works and text if you are interested in this let me know in the comments 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 now in laravel cash is a pretty important topic even if you're not aware of it caching is the act of transparently storing data for future use in an attempt to make applications run faster as a whole you can definitely say that cache looks like sessions and you can pretty much use them in the same exact way since you need to provide a key to store it now there are obviously differences between sessions and caches sessions are used to store data between page requests and cache is used to cache data per application therefore you usually store stuff like database queries and api calls in your cache just like sessions configurations of the cache are stored inside the convict folder right here where you have a file called cache.php if you scroll through the file you'll see a lot of similarities in any other convict file the most important one is actually at the top which is the cache driver right here if it isn't available it will store it in a default driver called file we're going to set the caching back-ends every situation might be different so you can change up your cache driver i'll switch screens real quick to my github repository because i added the different cache drivers the first one is the file driver which is the default one now the file driver will basically be the default value if you don't specify another driver what this will do is creating a new encrypted file per cache in your storage folder 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 server 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 clyde waze is their slogan moving dreams forward let's have a look at it let's go to visual studio codes scroll to the bottom open the storage folder framework folder where you will find a cache folder right here you can see the data folder is empty at the moment but once you store something inside your cache it will be visible right here now the most important question is probably can i use this for development yes you actually can and it's even faster than adding your cache in the database the second available driver is the array driver this is simply a array where you will store your cache there is an advantage right there because you don't need to configure a driver the only thing you need to do is to change your cache driver to array in your emv file then we got a harder driver to set up which is the database driver what this will do is storing in-memory for your current php process you do need to create a database table and this can easily be done through artisan by running the php artisan cache table command in my opinion there is a downside of storing your cache in the database the database driver can be overloaded when you get tons of caching on your site therefore i honestly don't recommend using the cache driver in real life examples it's pretty easy to set it you just need to set your cache driver equal to database now then we got radius and memcached and these are actually a bit more complex but they are actually very cool to use the radius driver basically uses an in-memory based caching technology while memcache does exactly the same but it requires a bit more server maintenance both of them can be used by setting the cache driver to either radius or memcached right let's navigate back to the code editor because we're going to perform some caching stuff just like sessions i usually prefer to access cache through the vacate so let's perform that let's close off our caching configuration file and right inside of the index method above review let's pull in the cash vacate so let's pry down cash pull in the illuminate support vacate colin colin get next to the vacate you can also call the cash global helper to do that you need to create a new variable let's say test and set it equal to the cache method and when you want to perform let's say the get method you just need to chain the get method to it now this line right here is exactly the same as the line above i prefer to use the vacate so let me get rid of this line of code we've already wrote down the get method right here which is used to pull the value of a cache that came with a request we've also got the pull method which is essentially the same as the get method but it removes the cache value after retrieving it we can't use the get method at the moment because we haven't set a cache so let's test it out let's add a dd right here and let's hit enter print out this line of code we don't need the semicolon save it navigate to brave open our local host and let me zoom in refresh the page now right here you can see that it has too few arguments inside the get method whenever you want to get a cache you need to provide a key so let's say key user save it go to brave refresh it right here the value is no because we don't have a cache whenever you want to create a cache you have to perform the put method so first let's navigate up right above our dd let's say cache colon colon instead of get perform the put method the put method accepts three parameters and two of them are actually required the first one will be the key so in single quotes let's say cache key comma single quotes then we need to provide the value that is related to the key so let's say this should be a cache key now let's change our get method to cache key navigate to brave refresh the page right here you can see that this should be a cache key has been printed out this works fine but a parameter is actually missing since you need to set an expiration date as the third parameter now this can be done with an integer which will represent the amount of seconds so right after a value add a comma and let's say 1000 which will be 1000 seconds i personally prefer to use the carbon object so let's change it up let's say now change the method of add day what this will do is save in your cache for 24 hours if we save it and navigate to the browser refresh it you won't see anything different in the output but it will all happen behind the scenes after 24 hours this cache will be deleted since we actually refreshed our page and our cache driver is equal to file we should be able to see a new file inside the cache folder if we navigate to visual studio code scroll down to the storage folder right here we have a new folder with a random name of 65 let's open it with a new file in here with an encrypted name let's open it right here you can see a encrypted key but the value is visible which is this should be a cash key let's close it off let's continue on with the next method which will be the add method right below our print method let's define the cash vacate column column add inside the add method we do need to provide a key and a value so let's say that the key is cash key again and let's say that the value is key number two if we save it refresh the page you can see that this should be a cash key is still printed out and there's actually a reason for it so if you try to add a new key with the add method that already exists it won't set it so key number 2 will not be set but it will change it to cache key 2 and change the get method to cache key 2 save it refresh the page you'll see that key number 2 has been printed out because cash key 2 which is the key does not exist inside our cache folder anymore the next method is the forever method and this is pretty much the same as the put method but you're not passing through an expiration date because it will never expire therefore the name of forever so let's remove everything after add let's call the forever method and inside the forever method we're basically going to pass in two parameters which is the key and the value again so let's say cash and the value is key2 save it navigate to the browser refresh it key2 has been printed out and if we actually open the new 83 file right here you actually won't see anything different than the cache with an expiration date but behind the scenes it knows that it can't expire well i've actually said it wrong because there's one method that will make it disappear if we go right below our forever method and say cache colon colon forget we need to pass in a key let's say cache key2 save it navigate to the browser refresh it you'll see that the output is null but if we navigate back to visual studio code now we open the well at least try to open the cache file you'll see that the folder is empty so it has indeed removed cache number two even though the method has an unexpired date time it literally deletes the cache from its stored location now at the moment you'll see that we have one caching file left right here so what we actually can do is to call the cache vacate colin colin and call the flush method now the flush method does not accept a parameter because it basically will delete every available cache in our application save it navigate to brave refresh the page the output is still null if we navigate to visual studio code you'll see that the data folder inside the cache folder has no caching files anymore the next method that we can perform on a cache is one that i've used a couple times but not really on a cache but on a session the has method will check whether there's a value set at the provided key so we do need to get rid of our flush and forget right here create an if statement where we're going to call the cash vacate colin collin has inside the has method we need to provide a key right now cache2 does exist copy it paste it in single quotes right here inside the if statement let's add a dd of cache does exist exist excuse me save it navigate to grave refresh it and right here you see that cache does exist now the next two methods are pretty useful because it lets you increase and decrease the value of an integer in a cache first let's get rid of our if statement then right below our forever method create a new cache vacate colon colon increment it accepts two parameters the first parameter will be the name of our cache in our case let's just call it cache key2 again it also accepts a second parameter so comma which will be the amount you want to increase your cache with let's pass in an integer of 1. in a programming language such as c-sharp this will actually give you an error now let me explain why inside the forever method that we have right here we set that the value of cache key2 should be a string of key2 since php is a loosely typed programming language it would treat the value as it was a zero so we will basically replace the value with zero and increase it with the second parameter we passed inside the increment method if we save it navigate to the browser refresh it you can indeed see that the output is 1 right now if we navigate back to visual studio code and change the value of cash key 2 to 4 save it navigate to brave refresh it you can see that the output is 5. so we will add the 4 that we add inside the forever method with the 1 of the increment method which will be 5. next to increasing a value you can obviously decrease it as well so to do that we need to replace increment with decrement save it navigate to brave refresh it and the output is tree so let's focus on a real live example right now i personally don't like storing cache in the database so instead of doing that i want to create a simple example where we store posts inside our cache we need to make sure that we set up a post migration model and dummy data with a login and register interface let's first pull in the authentication scaffolding inside the cli let's perform the composer require larval dash ui then we're going to pull in view ui with a php artisan ui view double dash hot and lastly we need to perform npm install double ampersand npm run dev all right webpack has been compiled successfully i've already created my database so if i open the erv file i have a database called larval underscore cache and my password is dario 1234 save it and close it off then we can run the php artisan migrate command it has migrated all tables so we can focus on the post right now so what do we need we first need a model so let's say php artisan make me a model called post we need a factory so a dash f we need a migration so m and we need a resource controller so r hit enter and let's actually start off by setting up our migration correctly let's open the database folder inside the root over directory migrations and it's the last one we do have an id then we have a table string which is the title we have a table called long text which will be the description then we have a table unsigned big integer which will be the user id right below our column timestamps let's create a table which will be the foreign key that will refer to the user id on the table so it references to id on the table so on users i've got a typo right here i need to close it off obviously save it let's run the php artisan migrate command it has created the post table so let's focus on our factory right now let's open the factories folder post factory scroll down inside the return method we basically have three columns that we need to fill in it's just in single quotes the user underscore id which will be a static one then we have the title which will be grabbed from this faker sentence that's a typo then we have the description as well which we will wear from this faker paragraph save it and let's navigate to brave because we need to create an account well actually let's remove ddd that we have right here save it navigate to brave and refresh the page let's change our endpoints to forward slash register let's create a new account right here so my name is code with dari cwd at gmail.com i have a secret password for you click on register i am logged in right now now we can finally use php artisan thinker to run our factory so in visual studio code let me make the terminal a little bit bigger let's say php artisan tinker and here we need to make sure that we call the entire path of our model so let's say app backslash models backslash post column colon factory now we're not going to add something inside the factory method but we're going to chain the count method and we're going to add 1000 rows in our database at the end we need to chain the create method as well if we hit enter this might take a minute because it will create 1000 rows well it actually did i am not gonna score up because that will take a while let's write down exit and what's next we got to make sure that we have an event and listener setup because it will fetch data from larall cache if the data does not exist in the cache so basically the 1000 rows it will fetch it from the database this will make sure that 1000 rows will not be loaded every single time a user enters the post page but it will only be cached once we're all familiar with events and listeners so let's perform the php artisan make colon event command called post created then we also need to create the listener so let's say php artisan make me a listener called post cache listener hit enter if we navigate to the app folder at the top and find the listeners folder that has been created for us with the post cache listener file we have a construct and a handle method we got to make sure that we remove the cache even when it hasn't been set so let's pull in the cache vacate let's say colin collin forget and the forget method accepts one parameter which will be the post key we haven't said it yet because we'll do it on the line below so let's say cache colin collin forever so create me a cache forever with a key of posts and the value will be grabbed from the post model so let's say post column in all right now we got to make sure that we hook our event into our model which can be done with the property dispatches event inside the post model so i actually haven't pulled in the post model all right that's better close the listener off open the modules folder post that php right below our use statement of hash factory or a trade excuse me create a new protected property dispatches events which is equal to an array let's go inside the array and hit enter the key will be created and the value is the event so let's say post create it pull it in column colon class now the next common step is to register our event and listener so let's navigate to the providers folder open the event service provider now right inside the protected property listing we first need to make sure that we register the event here so right below the register so right here let's say post created which is the event column column class let's add the xs operator brackets inside the brackets we need to call the listener which will be post cache listener column column class so what's next inside the index method of our post controller that we created our resource controller let's open it we got to make sure that we first dispatch the event and then get all the posts and put it inside the cache so let's do that let's say event let's pull in the support vacates event column column dispatch now what we're going to dispatch is a new event so a new post created then on the line below we're basically going to say well we have a variable posts which is equal to the cache method inside the cache method we got a key of posts comma we're not going to send back a value but a function inside the function we're basically going to say well return me a post well not to one post but all post so get outside of our post variable we're basically going to return a view called block.index and we're going to pass in the variable posts now before we can access the block.index page we got to create the route inside the web.php file right at the bottom or right here let's say route column colon get inside the get method we have an endpoint of forward slash block second param is a set of brackets so an array of the post controller column column class comma and the method will be index so let's create our route or our view so inside the views folder create a new folder called blog with a new file of index.blade.php let's add a piece of text of your 1000 rows have been added in the cache save it let me actually close off all my files because it happens a lot that it doesn't work because i haven't saved it look i haven't saved this file all right let's navigate back to brave change the endpoints to forward slash block and right here you can see that your 1000 rows have been added in the cache has been printed out but the most important thing is the cache folder so let's have a look and see if our cache has been added scroll down we have a folder right here let's see this is an old one i think that this is an old one as well 87 is a do you want to open it anyway let's say text editor right here you'll find a big json file which holds all of our posts now whenever we refresh the endpoint again you won't see a new folder because we are basically checking whether the cache file already exists or not and it does it will basically grab it all from the cache file whenever you refresh the blog page right now which will save you a lot of rendering time this was it for this video where i showed you how caching works in laravel and i've also showed you how you can store 1000 rows of your database in your cache which will save you a lot of rendering time for now this was it for this video i hope that you enjoyed it and if you did leave this video a thumbs up and if you're new to this channel please hit that subscribe button
Info
Channel: Code With Dary
Views: 2,478
Rating: undefined out of 5
Keywords: how to use cache, create public api with cache, laravel cache, laravel cache tutorial, how to use cache in laravel, what is caching in laravel, how to create cache in laravel, everything you need to know about laravel caching, basic use of cache in laravel, cache in laravel 8, laravel api cache, laravel cache view, laravel caching video, laravel cache api response, laravel cache example
Id: -NOOqIYEFwc
Channel Id: undefined
Length: 24min 18sec (1458 seconds)
Published: Mon Sep 20 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.