Home / Snippets / How to Guard and Unguard Model Property in Laravel
How to Guard and Unguard Model Property in Laravel cover

How to Guard and Unguard Model Property in Laravel

765

3 years ago

0 comments

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

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