When working with Laravel and Eloquent, you can take advantage of a bunch of cool helper functions that make inserting, updating, and deleting data from your database very easy.
Let's start with a quick example of how you can create a new post.
<?php
$post = new Post;
$post->title = 'My Awesome Post';
$post->body = 'This is the body of my post';
$post->active = 1;
$post->save();
That seems simple enough, right? But, Laravel makes it even easier. You can go one step further and create a new post like this:
<?php
$post = Post::create([
'title' => 'My Awesome Post',
'body' => 'This is the body of my post',
'active' => 1
]);
You will most likely get an error from the previous example unless you tell your Post Eloquent Model what values are allowed to be 'mass fillable'.
If you are going 'mass-assign' variables to your Post Model, you need to specify which ones can be fillable. You can easily do that by adding a protected $fillable
property to your class like so:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'body', 'active'];
}
There is also another way that you can specify this by using a $guarded
property. By default, all columns in an Eloquent Model guard against 'mass-assignment,' but if you set guarded
to an empty array, it will say that you can 'mass-assign' all columns.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
}
Make sure you are careful about allowing all columns to be mass-assigned. You'll want to make sure you verify all the fields the user is submitting, or you could run into a few vulnerabilities.
Here's a quick example:
<?php
public function createPost(Request $request){
$post = Post::create( $request->all() );
}
Say, that you submitted a form all the necessary info for a post, if you do not want to allow a user to set the active
column to 1
, they could easily open up Dev Tools and inject the following field into your form:
<input type="hidden" name="active" value="1">
Now, when they submit the form, this post will be set to active. If instead active
was added to the $guarded
array, this would prevent the user from "hacking your form".
That's it. Using the $fillable
and $guarded
properties allow you to specify which columns in your table (Eloquent Model) can be mass-assigned.