Posts Learn Components Snippets Categories Tags Tools About
/

How to Make Laravel Column Mass Assignable

Learn how to make column mass assignable in Laravel to allow multiple columns to be created and updated at the same time.

Created on Oct 24, 2021

141 views

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.

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

Load comments for How to Make Laravel Column Mass Assignable

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)