Laravel 5.8 – From The Ground Up
Lesson 13 of 52 · Laravel 5.8 Tutorial From Scratch – e13 – Eloquent Scopes & Mass Assignment · Education
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 https://www.coderstape.com
Resources
Course Source Code
https://github.com/coderstape/laravel-58-from-scratch
Hit us up on Twitter with any questions or comments @codertape (https://twitter.com/CodersTape)
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!