Home / Snippets / How to Make Laravel Column Mass Assignable
How to Make Laravel Column Mass Assignable cover

How to Make Laravel Column Mass Assignable

170

3 years ago

0 comments

To allow Laravel Columns to be mass assignable you can make use of the protected "$fillable" property from your Laravel Model. By specifying the columns inside the fillable property you will be able to create and update multiple columns at the same time using eloquent.

Make Columns Fillabe In Laravel


To make the columns fillable you can specify the "$fillable" property like below.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'slug', 'content', 'pubilshed_at'];
}
By specifying the columns like below now you will allow the "create" and "update" method to automatically assign the columns specified with the value hence "mass-assignable".
<?php

protected $fillable = ['name', 'slug', 'content', 'pubilshed_at'];

Create and Update Laravel Model


So now you can write your "create" and "update" code like the following.
<?php

use App\Models\Post;

$post = Post::create([
    'name' => 'Post 1 Here',
    'slug' => 'post-1-here',
    'content' => 'Your post 1 content here',
    'published_at' => now() // using carbon helper
]);

// Let's assume the code above having ID of 1
For the update part, you can refer to below.
<?php

use App\Models\Post;

// Get the 1st post
$post = Post::find(1);

$post->update([
    'name' => 'Post 1 UPDATED',
    'slug' => 'post-1-here',
    'content' => 'Your post 1 content UPDATED'
]);
The code above will work as expected and won't cause mass assignable errors. Do note that every time you are putting new columns in the array to update, you will need to update your "$fillable" fields aswell.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this