Posts Learn Components Snippets Categories Tags Tools new About
/

How to Guard and Unguard Model Property in Laravel

Learn how to guard and unguard all model property in Laravel

Created on Oct 24, 2021

21 views

The guarded property is the reverse of fillable property in the Laravel Model. If fillable specifies which fields to be mass assigned (allow the use of "create" or "update" method), guarded specifies which fields are not mass assignable.

Set Columns To Prevent Mass Assignable in Laravel


To set the columns to prevent mass assignable in Laravel you can "guard" it using the code example below.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['name', 'slug', 'content', 'pubilshed_at'];
}
By doing so the "name", "slug", "content" and "published_at" column won't be mass assignable.

Unguard Columns To Allow Mass Assignable in Laravel


To unguard and allow all columns to be mass assignable you can make use of the wildcard symbol.
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['*'];
}

Other Reads

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

)