Laravel 5.8 – From The Ground Up - Laravel 5.8 Tutorial From Scratch – e13 – Eloquent Scopes & Mass Assignment

Education, Programming

Laravel 5.8 – From The Ground Up

52 Lessons

Laravel 5.8 Tutorial From Scratch – e13 – Eloquent Scopes & Mass Assignment

continuing on I want to continue to talk about eloquent eloquent is the database over m that laravel uses behind the scenes now remember we chose SQLite for

our project so far but eloquent is able to handle many different drivers of databases and this is what makes it so powerful you only have to learn one eloquent and that will give you many

database options simply by changing the driver continuing on I want to show you one file that we've been using but we actually have not seen and that is our customer model if we go into our app

directory there is a customer that PHP file and so far we've actually used this file let me show you let me go to the customer controller and right down here we said new customer this customer that

we need up if we look up here is the app customer so we actually nude up this file and you may say well how is that even possible that file literally has nothing in it and that's partially right

remember we are extending model and if we click through the model model class is actually what contains all of the functionality that we've been using so far for example we use The Awl method

and there it is and this is the method that we use all right let's not dive too deep into that file this file here is the one that we are interested in so this file is your model this represents

a single row of a customer in our customer database when we ran the PHP artisan make model – M to make our migration we made this model file and we made our create customers migration now

so far we haven't had any need to touch this file at all but now I want to touch up on a new concept of laravel and that is scope so what is a scope imagine a scope as a filter right now we are

actually kind of using a scope when we say customers give me all of my customers we're active equals one we are scoping down our query by saying only give me those that are active and

then when we do the inverse we're using another scope now laravel has a very convenient way of declaring a scope and I'm going to show you that right now so if we go back to our app customer model

let's add a new public function here and the naming convention for a scope is it always starts with scope all lowercase and then the name of the scope starting with one capital case

so the first scope I want to make is an active scope so capital a active so scope active and the scope active needs to receive our query and then what we're gonna do here is we're going to return

query and then we're going to copy exactly what we had here before let's go back to the customer controller and we're simply going to take this logic right here copy that and bring it over

to our customer table and that's it so now we can say customers active get and that is the exact same thing except now we have a nice named method that we can call instead of just saying we're active

equals zero and hoping that somebody knows what that means we can use this active column all right let's do one more for the inactive customers so let's add a new public

function remember scope all lowercase in active and that's just a name for it and we'll accept the query and then let's return the query again and let's bring over the same exact code here so we're

gonna grab this where we'll copy that paste and then let's change this to inactive get so I think this reads much nicer active customers equals customers active get so get me my active customer

easy enough get me my inactive customers very simple alright let's check this out on the browser make sure we're still doing okay refresh and sure enough we're still getting the exact same thing

so that's a nice clean little refactor you can add as many scopes as you need to your project just make sure you label them properly that way it makes sense one thing you want to focus on not only

with scope but with laravel in general is that you want your code to read really nicely when we say something like get me my active customer that makes sense so that's a big focus on laravel

you want everything to have fluid syntax and everything to flow and read nicely so we want our active customers so customers active get ok inactive customers customers inactive get very

simple very fluid alright with that out of the way I want to do one more refactor let's go down to our store method we have this request and it validates and I'm saving it to this data

variable but we're actually not even using data variable and that is because up until this point I haven't really been able to use it the way that I would normally use it for demonstration

purposes but now that we have this file here we go ahead and open them side-by-side so you can see them so on the right hand side I've got my model and on the left hand side I've got my

controller so now that we know about our model on my controller I want to refactor all of this code here to not have all of this repetition we have quite a bit of repetition we have

this name here and then we have it here and then we have it here and then same thing for email and the same thing for active so what we can actually do is we can say the following

customer customer and then we could say create so create me a new customer and all I have to do is pass in data let me show you data here just so you see I'm gonna die and dump data let's go back to

the browser let's create a dummy customer we can make them active that's alright and there we are let me make this a little bigger so you see here that we have an array that contains our

validated data and this is very powerful because we know that any data that is inside of this array is data that we have specifically valid remember a user can always pop open

Chrome and add their own fields so you never want to trust what comes from your forms you always want to have every single field named and required or at least validated for the correct name

don't just grab the entire request and put it in your database hoping that the user didn't do any malicious activity always assume the worst so with this validated array we know

that each one of these fields is an actual field as a matter of fact I want to show you that because this is such an important concept let's go to my customers that blade and I'm gonna add a

dummy field here and let's just say email we're gonna call it random okay so this is just a random field that a user could have added on their end all right so we've added this field I just want to

show you this concept because it's so important so let me back up to my form and now you see that we have this new random field here so this is a user field we'll assume that a user opened up

Chrome and added this to our HTML and is now going to try to submit this to our server okay let's add customer but it didn't work so our array does not contain random so this is protecting us

this is a very very important concept about using validated data let's just say that I did want that random field however I didn't want it to be required it's an optional field how do we get

that request to give us that field well that's simple enough we're going to add it here and instead of writing required we're just gonna leave it blank so now that field will be included in our array

as I'll show you now but it's not required a user can leave it blank let's hit save let's try that one more time I'm gonna hit back I'm gonna submit one more time

and now we have our random field right here so it does show up but is not required let me delete that field there hit add customer again and now random is null and that's okay so that's how you

would a field that doesn't really have any validation rules something like it's optional or perhaps is not always there you can add it to your array in this

manner but just leave the validation rules empty all right with that out of the way now we know that we have our clean data right here and so going back to this we can say customer create a new

customer using this data and then we can get rid of all of these lines as a matter of fact we don't even need to save this so we can get rid of that line and then we'll return back so a much

cleaner controller now we're gonna run into a little bit of an error now which is gonna bring us to our next point but let's go ahead and test it anyway let's go back to our form I'm gonna hit back

we still have our random field let me go ahead and get rid of that since that was just for demonstrations let's get rid of that all right let's try this one more time final name email at email comm

active add customer and now we get this add name to fillable properties to allow mass assignment continuing on with the security measures that laravel ships with there's also two approaches to

actually being able to put stuff in your database you can be explicit about every single field that you will allow mass assignment and mass assignment is referring to back in our controller we

are massively assigning all of these fields right we're taking this chunk of data and we're just throwing it in the database and not particularly being careful about what we are sending in the

way we were in our previous example remember when we had customer name equals request name and the same for email and the same for active that's a very meticulous way of passing data to

your database the way that we've adopted now is called mass assignment we are taking this array and we're just throwing it in to our database so there are two solutions for this protection so

the first one is back in our model and that's app customer let's add a protected field called fillable and fillable is an array and by default this array is empty so in this array you

can specify every field that you will allow mass assignment on so let's do that now let's say name let's say email active so now we specifically said letter belt

it's okay for us to be mass assigning the name the email and the active column it's okay to do that go ahead and accept the request so let's go back here I will hit refresh continue then there

we go so we were able to add our final name with email at email com now I do want to show you another way and that is that you can basically turn off the protection altogether when you're

starting out having this fillable as your protection is a good idea however if you know you are always gonna follow good practices you can get rid of it all together I will comment that line out

and I will leave it there fillable example and let's make a new line here so let's add a new protected guarded and so guarded is the opposite of fillable so if we gave guarded an empty array it

means that nothing is guarded so in this particular instance if we said name is guarded then that means that we are not going to allow the name to be mass assigned but if we just pass in an empty

array it means nothing is guarded I'm gonna add a comment here we'll say guarded example and let's try the same form one more time we have our same filename that's okay

that customer and there we go so now we have to so that's working exactly how we expected so remember you can go the fillable way and this means that you are explicitly naming every field that you

will allow mass assignment on or you could go the guarded equals empty array which is telling laravel nothing is guarded because the array is empty so it's gonna look at the array and say is

there anything guarded the array is gonna be empty and let's go say nope nothing is guarded go ahead and mass assign any rows that you want personally I use guarded all the time

I don't ever do the fillable because I know that I will be doing something like this I will never do something like this where I say requests all I would never do that so I know that my fields are

protected I am running them through validation first and then I'm being very careful about what I pass into my create methods so in my personal case I always always use the guarded equals empty

array just so I don't have to worry about that but just know that that's what the mass assignable error is so to recap this episode we mostly work around this customer model over here so we

added a scope for our active and the naming convention for scope is you write scope and then the name of your scope so in our case active so here they are side by side this is how you declare it and

this is how you use it so we're saying customer give me all your active rows and what does active mean well active means that wherever the active column is set to one and then we

do the inverse scope in active go ahead and give me all of the fields where the active column is set to zero and so this is how we use it customer inactive get the idea with the

scopes is that it gives you a name because we're active equals zero today means something to you but maybe three months down the road when you come back you're gonna have to parse through your

code to figure out what you meant by saying active equals zero if I come back in three months and say customers inactive I immediately know I am just fetching my inactive customers and that

makes a sense as a second part of this video we refactor our store method we are now passing our data variable into our customer using the create method and this gave us a mass assignment error and

to fix that we went back to our model and we fix it in two different ways the first one is the fillable way where we are explicitly naming the fields that we are allowing masked assignment on and

the second way simply saying nothing is guarded disable mass assignment errors and then we tested everything on the browser we're back to where we started

but our code is a little bit cleaner thanks to all of these reef actors

Up next, let’s clean up our controller by extracting the logic for fetching an active/inactive customer into a scope. Then, let’s use validated data to create our new customers using the create() method.

For the best experience, follow along in our interactive school at

Course Source Code

Hit us up on Twitter with any questions or comments @codertape (

About This Course

Ready to get started on your path to Laravel Artisan? In this series, we are breaking down all of the basics of Laravel to get you comfortable using the world’s most popular PHP framework. Let’s get started!

    add to database laravel admin laravel artisan Artisan Command artisan commend create artisan console artisan laravel command authentication in laravel belongsto belongsto laravel example coding tutorials create artisan command create command artisan create new command artisan Create your own crud laravel crud laravel tutorial crud resource laravel crud with file upload custom artisan commands custom artisan commands laravel custom laravel database configuration laravel database relationship digital ocean dotenv eager loading eager loading in laravel eager loading vs lazy loading laravel eloquent eloquent accessors eloquent mutators eloquent orm feature testing laravel fetching data in laravel filesystem laravel form requests full stack vue gate and policy laravel google optimize hasmany hasmany laravel hasmany laravel example hasmany relationship in laravel hasone hasone relationship in laravel How to create how to queue email how to use queue installing laravel intervention image laravel laravel 5 laravel 5 auth laravel 5.4 queue laravel 5.5 queue laravel 5.8 laravel 5.8 artisan command laravel 5.8 artisan console laravel 5.8 auth tutorial laravel 5.8 authentication laravel 5.8 commands laravel 5.8 crud laravel 5.8 crud example laravel 5.8 custom middleware laravel 5.8 deprecations laravel 5.8 eager loading laravel 5.8 elixir laravel 5.8 event listeners laravel 5.8 events laravel 5.8 feature laravel 5.8 features laravel 5.8 global middleware laravel 5.8 install laravel 5.8 lazy loading laravel 5.8 listeners laravel 5.8 middleware laravel 5.8 multi auth laravel 5.8 named resource routes laravel 5.8 named routes laravel 5.8 new feature laravel 5.8 own artisan command laravel 5.8 queue laravel 5.8 queues laravel 5.8 routing laravel 5.8 telescope laravel 5.8 tutorial laravel 5.8 user auth laravel 5.8 user authentication laravel 5.8 what's new laravel 5.9 laravel admin permissions laravel api laravel artisan command laravel artisan console laravel assets laravel auth laravel auth role laravel authentication laravel authorization laravel axios post example laravel background process laravel background task laravel background worker laravel beginner to master laravel belongsto laravel belongsto vs hasone laravel belongstomany laravel best packages laravel best practices laravel best tutorial laravel bootstrap laravel command laravel command line laravel commands tutorial laravel composer install laravel connect db laravel console command laravel console testing laravel contact form send email laravel controllers laravel create laravel crud laravel crud policy laravel custom command laravel custom middleware laravel database laravel database configuration laravel database relationships laravel database seeder laravel database settings laravel db seed laravel db settings laravel debugging laravel deploy aws laravel deploy digital ocean laravel deploy on digitalocean laravel deploy on server laravel deploy to production laravel deployment laravel digitalocean laravel drag and drop file upload laravel dropzone file upload laravel dropzone image upload laravel e-commerce laravel eager loading laravel eager loading tutorial laravel eager loading with condition laravel elixir laravel eloquent laravel eloquent belongsto laravel eloquent crud laravel eloquent hasmany laravel eloquent where laravel eloquest tutorial laravel events and queue laravel events tutorial laravel factory laravel feature test laravel feature testing laravel fetching data from database laravel file storage laravel fillable example laravel flash message notification laravel for beginners laravel form validation laravel forms laravel forms bootstrap snippets laravel from scratch laravel from the ground up laravel front end laravel frontend tutorial laravel gate and policy tutorial laravel global middleware laravel hasmany laravel hasone laravel i18n laravel installation laravel installation mac laravel intervention image tutorial laravel javascript tutorial laravel jobs queue laravel language laravel language switcher laravel language tutorial laravel languages laravel lazy loading laravel listener event laravel listeners laravel localization laravel login laravel mailable tutorial laravel many to many relationship example laravel markdown email laravel markdown mail laravel mass assignment laravel middleware laravel migrate fresh laravel mix laravel mix 5.8 laravel mix vue laravel model factory tutorial laravel multiple language laravel mysql json laravel named resource routes laravel named routes laravel new features laravel news laravel nginx laravel node modules laravel npm install laravel npm run watch error laravel one to one laravel paginate laravel paginate link laravel pagination laravel pagination 5.8 laravel pagination links laravel pagination tutorial laravel phpunit laravel phpunit testing laravel pivot table example laravel policy laravel preview laravel query optimization laravel queue laravel queue event listener laravel react laravel register user laravel registration laravel registration validation laravel relationships laravel reset password laravel role middleware laravel role permission laravel roles laravel route group middleware laravel routes laravel routing laravel routing with parameters laravel sass laravel save file to database laravel scopes laravel seo tutorial laravel server laravel session data laravel ssl laravel supervisor laravel tailwind css laravel tailwind setup laravel tdd laravel tdd tutorial laravel telescope laravel telescope installation laravel telescope tutorial laravel test driven development laravel test workflow laravel testing laravel testing controllers laravel testing tutorial laravel tools laravel translation laravel tutorial laravel tutorial for beginners laravel ubuntu server laravel ubuntu tutorial laravel unit testing controllers laravel upload file laravel upload image to storage laravel upload multiple files at once laravel upload multiple image to database laravel upload multiple images laravel url slug laravel vue laravel vue js crud laravel vue setup laravel vue tutorial laravel vue.js laravel webpack error laravel webpack tutorial lazy loading lazy loading laravel lazy loading vs eager loading learn laravel learn laravel framework step by step localization in laravel localization laravel many to many laravel mvc tutorial for beginners in php mvc tutorial laravel mysql mysql relational database mysql relationship n + 1 problem n + 1 problem laravel new artisan command npm install npm run dev npm run watch laravel one to many one to one one to one laravel own artisan command pagination pagination bootstrap pagination bootstrap php mysql pagination laravel pagination laravel bootstrap pagination links pagination php php php artisan php carbon immutable php framework php framework 2019 php what's new 2019 phpunit phpunit laravel phpunit testing pivot laravel policy laravel polymorphic relationships queue and events queue email queue for laravel queue jobs queue laravel 5.8 registration form relationship laravel eloquent relationship mysql restful controller role permission in laravel roles laravel route model binding laravel routing in laravel save image to database seo friendly seo friendly content writing seo friendly website seo laravel seo optimization simple pagination laravel slugify sqlite relational database sqlite relationships between tables symfony command console symfony laravel tailwind css tailwind laravel mix telescope laravel tutorial laravel unit testing unit testing laravel upload file laravel upload file php upload image laravel upload image to database php upload images laravel upload multiple files in php url slug laravel url slug php vue vue.js vuejs laravel why use laravel queue why use queue