exclamation WARNING You're browsing the documentation for an old version of Laravel. Consider upgrading your project to Laravel 11.x .

Eloquent: Getting Started

Introduction, generating model classes, table names, primary keys, uuid and ulid keys, database connections, default attribute values, configuring eloquent strictness, collections, chunking results.

  • Chunk Using Lazy Collections

Advanced Subqueries

Retrieving or creating models, retrieving aggregates, mass assignment, soft deleting, querying soft deleted models, pruning models, replicating models, global scopes, local scopes, comparing models, using closures, muting events.

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well.

Before getting started, be sure to configure a database connection in your application's config/database.php configuration file. For more information on configuring your database, check out the database configuration documentation .

Laravel Bootcamp

If you're new to Laravel, feel free to jump into the Laravel Bootcamp . The Laravel Bootcamp will walk you through building your first Laravel application using Eloquent. It's a great way to get a tour of everything that Laravel and Eloquent have to offer.

To get started, let's create an Eloquent model. Models typically live in the app\Models directory and extend the Illuminate\Database\Eloquent\Model class. You may use the make:model Artisan command to generate a new model:

If you would like to generate a database migration when you generate the model, you may use the --migration or -m option:

You may generate various other types of classes when generating a model, such as factories, seeders, policies, controllers, and form requests. In addition, these options may be combined to create multiple classes at once:

Inspecting Models

Sometimes it can be difficult to determine all of a model's available attributes and relationships just by skimming its code. Instead, try the model:show Artisan command, which provides a convenient overview of all the model's attributes and relations:

Eloquent Model Conventions

Models generated by the make:model command will be placed in the app/Models directory. Let's examine a basic model class and discuss some of Eloquent's key conventions:

After glancing at the example above, you may have noticed that we did not tell Eloquent which database table corresponds to our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table, while an AirTrafficController model would store records in an air_traffic_controllers table.

If your model's corresponding database table does not fit this convention, you may manually specify the model's table name by defining a table property on the model:

Eloquent will also assume that each model's corresponding database table has a primary key column named id . If necessary, you may define a protected $primaryKey property on your model to specify a different column that serves as your model's primary key:

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that Eloquent will automatically cast the primary key to an integer. If you wish to use a non-incrementing or a non-numeric primary key you must define a public $incrementing property on your model that is set to false :

If your model's primary key is not an integer, you should define a protected $keyType property on your model. This property should have a value of string :

"Composite" Primary Keys

Eloquent requires each model to have at least one uniquely identifying "ID" that can serve as its primary key. "Composite" primary keys are not supported by Eloquent models. However, you are free to add additional multi-column, unique indexes to your database tables in addition to the table's uniquely identifying primary key.

Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead. UUIDs are universally unique alpha-numeric identifiers that are 36 characters long.

If you would like a model to use a UUID key instead of an auto-incrementing integer key, you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model. Of course, you should ensure that the model has a UUID equivalent primary key column :

By default, The HasUuids trait will generate "ordered" UUIDs for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically.

You can override the UUID generation process for a given model by defining a newUniqueId method on the model. In addition, you may specify which columns should receive UUIDs by defining a uniqueIds method on the model:

If you wish, you may choose to utilize "ULIDs" instead of UUIDs. ULIDs are similar to UUIDs; however, they are only 26 characters in length. Like ordered UUIDs, ULIDs are lexicographically sortable for efficient database indexing. To utilize ULIDs, you should use the Illuminate\Database\Eloquent\Concerns\HasUlids trait on your model. You should also ensure that the model has a ULID equivalent primary key column :

By default, Eloquent expects created_at and updated_at columns to exist on your model's corresponding database table. Eloquent will automatically set these column's values when models are created or updated. If you do not want these columns to be automatically managed by Eloquent, you should define a $timestamps property on your model with a value of false :

If you need to customize the format of your model's timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database as well as their format when the model is serialized to an array or JSON:

If you need to customize the names of the columns used to store the timestamps, you may define CREATED_AT and UPDATED_AT constants on your model:

If you would like to perform model operations without the model having its updated_at timestamp modified, you may operate on the model within a closure given to the withoutTimestamps method:

By default, all Eloquent models will use the default database connection that is configured for your application. If you would like to specify a different connection that should be used when interacting with a particular model, you should define a $connection property on the model:

By default, a newly instantiated model instance will not contain any attribute values. If you would like to define the default values for some of your model's attributes, you may define an $attributes property on your model. Attribute values placed in the $attributes array should be in their raw, "storable" format as if they were just read from the database:

Laravel offers several methods that allow you to configure Eloquent's behavior and "strictness" in a variety of situations.

First, the preventLazyLoading method accepts an optional boolean argument that indicates if lazy loading should be prevented. For example, you may wish to only disable lazy loading in non-production environments so that your production environment will continue to function normally even if a lazy loaded relationship is accidentally present in production code. Typically, this method should be invoked in the boot method of your application's AppServiceProvider :

Also, you may instruct Laravel to throw an exception when attempting to fill an unfillable attribute by invoking the preventSilentlyDiscardingAttributes method. This can help prevent unexpected errors during local development when attempting to set an attribute that has not been added to the model's fillable array:

Retrieving Models

Once you have created a model and its associated database table , you are ready to start retrieving data from your database. You can think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model. The model's all method will retrieve all of the records from the model's associated database table:

Building Queries

The Eloquent all method will return all of the results in the model's table. However, since each Eloquent model serves as a query builder , you may add additional constraints to queries and then invoke the get method to retrieve the results:

Since Eloquent models are query builders, you should review all of the methods provided by Laravel's query builder . You may use any of these methods when writing your Eloquent queries.

Refreshing Models

If you already have an instance of an Eloquent model that was retrieved from the database, you can "refresh" the model using the fresh and refresh methods. The fresh method will re-retrieve the model from the database. The existing model instance will not be affected:

The refresh method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well:

As we have seen, Eloquent methods like all and get retrieve multiple records from the database. However, these methods don't return a plain PHP array. Instead, an instance of Illuminate\Database\Eloquent\Collection is returned.

The Eloquent Collection class extends Laravel's base Illuminate\Support\Collection class, which provides a variety of helpful methods for interacting with data collections. For example, the reject method may be used to remove models from a collection based on the results of an invoked closure:

In addition to the methods provided by Laravel's base collection class, the Eloquent collection class provides a few extra methods that are specifically intended for interacting with collections of Eloquent models.

Since all of Laravel's collections implement PHP's iterable interfaces, you may loop over collections as if they were an array:

Your application may run out of memory if you attempt to load tens of thousands of Eloquent records via the all or get methods. Instead of using these methods, the chunk method may be used to process large numbers of models more efficiently.

The chunk method will retrieve a subset of Eloquent models, passing them to a closure for processing. Since only the current chunk of Eloquent models is retrieved at a time, the chunk method will provide significantly reduced memory usage when working with a large number of models:

The first argument passed to the chunk method is the number of records you wish to receive per "chunk". The closure passed as the second argument will be invoked for each chunk that is retrieved from the database. A database query will be executed to retrieve each chunk of records passed to the closure.

If you are filtering the results of the chunk method based on a column that you will also be updating while iterating over the results, you should use the chunkById method. Using the chunk method in these scenarios could lead to unexpected and inconsistent results. Internally, the chunkById method will always retrieve models with an id column greater than the last model in the previous chunk:

Chunking Using Lazy Collections

The lazy method works similarly to the chunk method in the sense that, behind the scenes, it executes the query in chunks. However, instead of passing each chunk directly into a callback as is, the lazy method returns a flattened LazyCollection of Eloquent models, which lets you interact with the results as a single stream:

If you are filtering the results of the lazy method based on a column that you will also be updating while iterating over the results, you should use the lazyById method. Internally, the lazyById method will always retrieve models with an id column greater than the last model in the previous chunk:

You may filter the results based on the descending order of the id using the lazyByIdDesc method.

Similar to the lazy method, the cursor method may be used to significantly reduce your application's memory consumption when iterating through tens of thousands of Eloquent model records.

The cursor method will only execute a single database query; however, the individual Eloquent models will not be hydrated until they are actually iterated over. Therefore, only one Eloquent model is kept in memory at any given time while iterating over the cursor.

Since the cursor method only ever holds a single Eloquent model in memory at a time, it cannot eager load relationships. If you need to eager load relationships, consider using the lazy method instead.

Internally, the cursor method uses PHP generators to implement this functionality:

The cursor returns an Illuminate\Support\LazyCollection instance. Lazy collections allow you to use many of the collection methods available on typical Laravel collections while only loading a single model into memory at a time:

Although the cursor method uses far less memory than a regular query (by only holding a single Eloquent model in memory at a time), it will still eventually run out of memory. This is due to PHP's PDO driver internally caching all raw query results in its buffer . If you're dealing with a very large number of Eloquent records, consider using the lazy method instead.

Subquery Selects

Eloquent also offers advanced subquery support, which allows you to pull information from related tables in a single query. For example, let's imagine that we have a table of flight destinations and a table of flights to destinations. The flights table contains an arrived_at column which indicates when the flight arrived at the destination.

Using the subquery functionality available to the query builder's select and addSelect methods, we can select all of the destinations and the name of the flight that most recently arrived at that destination using a single query:

Subquery Ordering

In addition, the query builder's orderBy function supports subqueries. Continuing to use our flight example, we may use this functionality to sort all destinations based on when the last flight arrived at that destination. Again, this may be done while executing a single database query:

Retrieving Single Models / Aggregates

In addition to retrieving all of the records matching a given query, you may also retrieve single records using the find , first , or firstWhere methods. Instead of returning a collection of models, these methods return a single model instance:

Sometimes you may wish to perform some other action if no results are found. The findOr and firstOr methods will return a single model instance or, if no results are found, execute the given closure. The value returned by the closure will be considered the result of the method:

Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

If the ModelNotFoundException is not caught, a 404 HTTP response is automatically sent back to the client:

The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the attributes resulting from merging the first array argument with the optional second array argument:

The firstOrNew method, like firstOrCreate , will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to manually call the save method to persist it:

When interacting with Eloquent models, you may also use the count , sum , max , and other aggregate methods provided by the Laravel query builder . As you might expect, these methods return a scalar value instead of an Eloquent model instance:

Inserting and Updating Models

Of course, when using Eloquent, we don't only need to retrieve models from the database. We also need to insert new records. Thankfully, Eloquent makes it simple. To insert a new record into the database, you should instantiate a new model instance and set attributes on the model. Then, call the save method on the model instance:

In this example, we assign the name field from the incoming HTTP request to the name attribute of the App\Models\Flight model instance. When we call the save method, a record will be inserted into the database. The model's created_at and updated_at timestamps will automatically be set when the save method is called, so there is no need to set them manually.

Alternatively, you may use the create method to "save" a new model using a single PHP statement. The inserted model instance will be returned to you by the create method:

However, before using the create method, you will need to specify either a fillable or guarded property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default. To learn more about mass assignment, please consult the mass assignment documentation .

The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it and set any attributes you wish to update. Then, you should call the model's save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value:

Mass Updates

Updates can also be performed against models that match a given query. In this example, all flights that are active and have a destination of San Diego will be marked as delayed:

The update method expects an array of column and value pairs representing the columns that should be updated. The update method returns the number of affected rows.

When issuing a mass update via Eloquent, the saving , saved , updating , and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

Examining Attribute Changes

Eloquent provides the isDirty , isClean , and wasChanged methods to examine the internal state of your model and determine how its attributes have changed from when the model was originally retrieved.

The isDirty method determines if any of the model's attributes have been changed since the model was retrieved. You may pass a specific attribute name or an array of attributes to the isDirty method to determine if any of the attributes are "dirty". The isClean method will determine if an attribute has remained unchanged since the model was retrieved. This method also accepts an optional attribute argument:

The wasChanged method determines if any attributes were changed when the model was last saved within the current request cycle. If needed, you may pass an attribute name to see if a particular attribute was changed:

The getOriginal method returns an array containing the original attributes of the model regardless of any changes to the model since it was retrieved. If needed, you may pass a specific attribute name to get the original value of a particular attribute:

You may use the create method to "save" a new model using a single PHP statement. The inserted model instance will be returned to you by the method:

However, before using the create method, you will need to specify either a fillable or guarded property on your model class. These properties are required because all Eloquent models are protected against mass assignment vulnerabilities by default.

A mass assignment vulnerability occurs when a user passes an unexpected HTTP request field and that field changes a column in your database that you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed to your model's create method, allowing the user to escalate themselves to an administrator.

So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model. For example, let's make the name attribute of our Flight model mass assignable:

Once you have specified which attributes are mass assignable, you may use the create method to insert a new record in the database. The create method returns the newly created model instance:

If you already have a model instance, you may use the fill method to populate it with an array of attributes:

Mass Assignment and JSON Columns

When assigning JSON columns, each column's mass assignable key must be specified in your model's $fillable array. For security, Laravel does not support updating nested JSON attributes when using the guarded property:

Allowing Mass Assignment

If you would like to make all of your attributes mass assignable, you may define your model's $guarded property as an empty array. If you choose to unguard your model, you should take special care to always hand-craft the arrays passed to Eloquent's fill , create , and update methods:

Mass Assignment Exceptions

By default, attributes that are not included in the $fillable array are silently discarded when performing mass-assignment operations. In production, this is expected behavior; however, during local development it can lead to confusion as to why model changes are not taking effect.

If you wish, you may instruct Laravel to throw an exception when attempting to fill an unfillable attribute by invoking the preventSilentlyDiscardingAttributes method. Typically, this method should be invoked within the boot method of one of your application's service providers:

Occasionally, you may need to update an existing model or create a new model if no matching model exists. Like the firstOrCreate method, the updateOrCreate method persists the model, so there's no need to manually call the save method.

In the example below, if a flight exists with a departure location of Oakland and a destination location of San Diego , its price and discounted columns will be updated. If no such flight exists, a new flight will be created which has the attributes resulting from merging the first argument array with the second argument array:

If you would like to perform multiple "upserts" in a single query, then you should use the upsert method instead. The method's first argument consists of the values to insert or update, while the second argument lists the column(s) that uniquely identify records within the associated table. The method's third and final argument is an array of the columns that should be updated if a matching record already exists in the database. The upsert method will automatically set the created_at and updated_at timestamps if timestamps are enabled on the model:

All databases except SQL Server require the columns in the second argument of the upsert method to have a "primary" or "unique" index. In addition, the MySQL database driver ignores the second argument of the upsert method and always uses the "primary" and "unique" indexes of the table to detect existing records.

Deleting Models

To delete a model, you may call the delete method on the model instance:

You may call the truncate method to delete all of the model's associated database records. The truncate operation will also reset any auto-incrementing IDs on the model's associated table:

Deleting an Existing Model by its Primary Key

In the example above, we are retrieving the model from the database before calling the delete method. However, if you know the primary key of the model, you may delete the model without explicitly retrieving it by calling the destroy method. In addition to accepting the single primary key, the destroy method will accept multiple primary keys, an array of primary keys, or a collection of primary keys:

The destroy method loads each model individually and calls the delete method so that the deleting and deleted events are properly dispatched for each model.

Deleting Models Using Queries

Of course, you may build an Eloquent query to delete all models matching your query's criteria. In this example, we will delete all flights that are marked as inactive. Like mass updates, mass deletes will not dispatch model events for the models that are deleted:

When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be dispatched for the deleted models. This is because the models are never actually retrieved when executing the delete statement.

In addition to actually removing records from your database, Eloquent can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model indicating the date and time at which the model was "deleted". To enable soft deletes for a model, add the Illuminate\Database\Eloquent\SoftDeletes trait to the model:

The SoftDeletes trait will automatically cast the deleted_at attribute to a DateTime / Carbon instance for you.

You should also add the deleted_at column to your database table. The Laravel schema builder contains a helper method to create this column:

Now, when you call the delete method on the model, the deleted_at column will be set to the current date and time. However, the model's database record will be left in the table. When querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.

To determine if a given model instance has been soft deleted, you may use the trashed method:

Restoring Soft Deleted Models

Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model, you may call the restore method on a model instance. The restore method will set the model's deleted_at column to null :

You may also use the restore method in a query to restore multiple models. Again, like other "mass" operations, this will not dispatch any model events for the models that are restored:

The restore method may also be used when building relationship queries:

Permanently Deleting Models

Sometimes you may need to truly remove a model from your database. You may use the forceDelete method to permanently remove a soft deleted model from the database table:

You may also use the forceDelete method when building Eloquent relationship queries:

Including Soft Deleted Models

As noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to be included in a query's results by calling the withTrashed method on the query:

The withTrashed method may also be called when building a relationship query:

Retrieving Only Soft Deleted Models

The onlyTrashed method will retrieve only soft deleted models:

Sometimes you may want to periodically delete models that are no longer needed. To accomplish this, you may add the Illuminate\Database\Eloquent\Prunable or Illuminate\Database\Eloquent\MassPrunable trait to the models you would like to periodically prune. After adding one of the traits to the model, implement a prunable method which returns an Eloquent query builder that resolves the models that are no longer needed:

When marking models as Prunable , you may also define a pruning method on the model. This method will be called before the model is deleted. This method can be useful for deleting any additional resources associated with the model, such as stored files, before the model is permanently removed from the database:

After configuring your prunable model, you should schedule the model:prune Artisan command in your application's App\Console\Kernel class. You are free to choose the appropriate interval at which this command should be run:

Behind the scenes, the model:prune command will automatically detect "Prunable" models within your application's app/Models directory. If your models are in a different location, you may use the --model option to specify the model class names:

If you wish to exclude certain models from being pruned while pruning all other detected models, you may use the --except option:

You may test your prunable query by executing the model:prune command with the --pretend option. When pretending, the model:prune command will simply report how many records would be pruned if the command were to actually run:

Soft deleting models will be permanently deleted ( forceDelete ) if they match the prunable query.

Mass Pruning

When models are marked with the Illuminate\Database\Eloquent\MassPrunable trait, models are deleted from the database using mass-deletion queries. Therefore, the pruning method will not be invoked, nor will the deleting and deleted model events be dispatched. This is because the models are never actually retrieved before deletion, thus making the pruning process much more efficient:

You may create an unsaved copy of an existing model instance using the replicate method. This method is particularly useful when you have model instances that share many of the same attributes:

To exclude one or more attributes from being replicated to the new model, you may pass an array to the replicate method:

Query Scopes

Global scopes allow you to add constraints to all queries for a given model. Laravel's own soft delete functionality utilizes global scopes to only retrieve "non-deleted" models from the database. Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints.

Generating Scopes

To generate a new global scope, you may invoke the make:scope Artisan command, which will place the generated scope in your application's app/Models/Scopes directory:

Writing Global Scopes

Writing a global scope is simple. First, use the make:scope command to generate a class that implements the Illuminate\Database\Eloquent\Scope interface. The Scope interface requires you to implement one method: apply . The apply method may add where constraints or other types of clauses to the query as needed:

If your global scope is adding columns to the select clause of the query, you should use the addSelect method instead of select . This will prevent the unintentional replacement of the query's existing select clause.

Applying Global Scopes

To assign a global scope to a model, you may simply place the ScopedBy attribute on the model:

Or, you may manually register the global scope by overriding the model's booted method and invoke the model's addGlobalScope method. The addGlobalScope method accepts an instance of your scope as its only argument:

After adding the scope in the example above to the App\Models\User model, a call to the User::all() method will execute the following SQL query:

Anonymous Global Scopes

Eloquent also allows you to define global scopes using closures, which is particularly useful for simple scopes that do not warrant a separate class of their own. When defining a global scope using a closure, you should provide a scope name of your own choosing as the first argument to the addGlobalScope method:

Removing Global Scopes

If you would like to remove a global scope for a given query, you may use the withoutGlobalScope method. This method accepts the class name of the global scope as its only argument:

Or, if you defined the global scope using a closure, you should pass the string name that you assigned to the global scope:

If you would like to remove several or even all of the query's global scopes, you may use the withoutGlobalScopes method:

Local scopes allow you to define common sets of query constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, prefix an Eloquent model method with scope .

Scopes should always return the same query builder instance or void :

Utilizing a Local Scope

Once the scope has been defined, you may call the scope methods when querying the model. However, you should not include the scope prefix when calling the method. You can even chain calls to various scopes:

Combining multiple Eloquent model scopes via an or query operator may require the use of closures to achieve the correct logical grouping :

However, since this can be cumbersome, Laravel provides a "higher order" orWhere method that allows you to fluently chain scopes together without the use of closures:

Dynamic Scopes

Sometimes you may wish to define a scope that accepts parameters. To get started, just add your additional parameters to your scope method's signature. Scope parameters should be defined after the $query parameter:

Once the expected arguments have been added to your scope method's signature, you may pass the arguments when calling the scope:

Sometimes you may need to determine if two models are the "same" or not. The is and isNot methods may be used to quickly verify two models have the same primary key, table, and database connection or not:

The is and isNot methods are also available when using the belongsTo , hasOne , morphTo , and morphOne relationships . This method is particularly helpful when you would like to compare a related model without issuing a query to retrieve that model:

Want to broadcast your Eloquent events directly to your client-side application? Check out Laravel's model event broadcasting .

Eloquent models dispatch several events, allowing you to hook into the following moments in a model's lifecycle: retrieved , creating , created , updating , updated , saving , saved , deleting , deleted , trashed , forceDeleting , forceDeleted , restoring , restored , and replicating .

The retrieved event will dispatch when an existing model is retrieved from the database. When a new model is saved for the first time, the creating and created events will dispatch. The updating / updated events will dispatch when an existing model is modified and the save method is called. The saving / saved events will dispatch when a model is created or updated - even if the model's attributes have not been changed. Event names ending with -ing are dispatched before any changes to the model are persisted, while events ending with -ed are dispatched after the changes to the model are persisted.

To start listening to model events, define a $dispatchesEvents property on your Eloquent model. This property maps various points of the Eloquent model's lifecycle to your own event classes . Each model event class should expect to receive an instance of the affected model via its constructor:

After defining and mapping your Eloquent events, you may use event listeners to handle the events.

When issuing a mass update or delete query via Eloquent, the saved , updated , deleting , and deleted model events will not be dispatched for the affected models. This is because the models are never actually retrieved when performing mass updates or deletes.

Instead of using custom event classes, you may register closures that execute when various model events are dispatched. Typically, you should register these closures in the booted method of your model:

If needed, you may utilize queueable anonymous event listeners when registering model events. This will instruct Laravel to execute the model event listener in the background using your application's queue :

Defining Observers

If you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. Observer classes have method names which reflect the Eloquent events you wish to listen for. Each of these methods receives the affected model as their only argument. The make:observer Artisan command is the easiest way to create a new observer class:

This command will place the new observer in your app/Observers directory. If this directory does not exist, Artisan will create it for you. Your fresh observer will look like the following:

To register an observer, you may place the ObservedBy attribute on the corresponding model:

Or, you may manually register an observer by calling the observe method on the model you wish to observe. You may register observers in the boot method of your application's App\Providers\EventServiceProvider service provider:

There are additional events an observer can listen to, such as saving and retrieved . These events are described within the events documentation.

Observers and Database Transactions

When models are being created within a database transaction, you may want to instruct an observer to only execute its event handlers after the database transaction is committed. You may accomplish this by implementing the ShouldHandleEventsAfterCommit interface on your observer. If a database transaction is not in progress, the event handlers will execute immediately:

You may occasionally need to temporarily "mute" all events fired by a model. You may achieve this using the withoutEvents method. The withoutEvents method accepts a closure as its only argument. Any code executed within this closure will not dispatch model events, and any value returned by the closure will be returned by the withoutEvents method:

Saving a Single Model Without Events

Sometimes you may wish to "save" a given model without dispatching any events. You may accomplish this using the saveQuietly method:

You may also "update", "delete", "soft delete", "restore", and "replicate" a given model without dispatching any events:

Add [title] to fillable property to allow mass assignment on [App\Models\Post]. in laravel

Answered on: Sunday 21 April, 2024 / Duration: 16 min read

Programming Language: PHP , Popularity : 4/10

Solution 1:

To add a title field to the fillable property in the Post model in Laravel, you need to modify the $fillable array in the Post model. This will allow you to mass assign the title field when creating or updating a Post instance.

Here is an example of how you can add the title field to the fillable property in the Post model:

In this example, we added the 'title' field to the $fillable array, along with the existing 'content' and 'user_id' fields. This will allow you to mass assign the title field when creating or updating a Post instance.

To demonstrate how this works, you can create a new Post instance and mass assign the title field like this:

In this example, we are creating a new Post instance and mass assigning the 'title', 'content', and 'user_id' fields using the fill() method. The title field is included in the fillable property, so it will be accepted for mass assignment.

When you save the Post instance, the title field will be saved to the database along with the other fields. You can verify this by retrieving the Post instance and accessing the title field:

This demonstrates how you can add a title field to the fillable property in the Post model in Laravel and use mass assignment to set the title field when creating or updating Post instances.

Solution 2:

Explanation:

In Laravel, models are used to represent database tables. By default, when you mass assign data to a model, only certain attributes are allowed to be set. This is a security measure to prevent unexpected or malicious data from being inserted into your database.

To allow mass assignment on a specific model, you need to explicitly specify which attributes can be mass assigned. This can be done using the protected $fillable property.

Code Example:

In this example, we have defined the fillable property on the Post model. This means that when mass assigning data to a Post model, only the title and body attributes will be set. Any other attributes that are not included in the fillable array will be ignored.

When you mass assign data to a Post model, only the title and body attributes will be set. Any other attributes that are not included in the fillable array will be ignored.

For example, the following code will only set the title and body attributes of the $post model:

However, the following code will not set the author_id attribute of the $post model because it is not included in the fillable array:

* Security: The fillable property helps to prevent unexpected or malicious data from being inserted into your database. * Control: You can explicitly specify which attributes can be mass assigned, giving you more control over the data that is saved to your database. * Error Handling: If you try to mass assign a value to an attribute that is not included in the fillable array, Laravel will throw an exception, making it easier to identify and fix errors.

Solution 3:

In Laravel, mass assignment is the process of assigning multiple attributes to a model at once. By default, Laravel protects your models from mass assignment to prevent security vulnerabilities. To enable mass assignment for certain properties, you need to add them to the $fillable array in your model.

To add a title property to the fillable properties to allow mass assignment on the App\Models\Post model, follow these steps:

1. Open the Post model located at app/Models/Post.php .

2. Add the title property to the $fillable array if it is not already present. The $fillable array should look like this:

Here's an example of how to update the Post model:

After making these changes, you can mass-assign the title property when creating or updating a Post model. Here's an example of creating a new Post with the title property using the create method:

This creates a new Post record with the specified title property. Note that the title property should be in the $postData array when creating or updating the Post model.

Similarly, you can update an existing Post model using the update method and mass-assign the title property. Here's an example:

This updates the existing Post record with the specified title property. Again, the title property should be in the $postData array when updating the Post model.

Remember, mass-assigning properties without explicitly defining them as fillable can lead to security vulnerabilities like mass-assignment attacks. Therefore, it's recommended to define only the necessary properties in the $fillable array and avoid including sensitive properties.

More Articles :

Select in php mysql.

Answered on: Sunday 21 April, 2024 / Duration: 5-10 min read

Programming Language : PHP , Popularity : 6/10

declare variable in view for loop laravel

Programming Language : PHP , Popularity : 8/10

php csv string to associative array with column name

Without form request validation how can we use this , e: unable to locate package php7.2-mbstring.

Programming Language : PHP , Popularity : 4/10

.env example laravel

Programming Language : PHP , Popularity : 3/10

"codeigniter 4" cart

Programming Language : PHP , Popularity : 10/10

symfony command to check entities

Package phpoffice/phpexcel is abandoned, you should avoid using it. use phpoffice/phpspreadsheet instead., php time format, php remove emoji from string, "message": "call to a member function cannot() on null", "exception": "symfony\\component\\debug\\exception\\fatalthrowableerror",.

Programming Language : PHP , Popularity : 9/10

php code for if $id is not empty, do an action

Convert time to decimal php, "\u00e9" php.

Programming Language : PHP , Popularity : 7/10

->when($min_age, function ($query) use ($min_age){ $mindate = now()->subYears($min_age)->format('Y-m-d'); $query->whereHas('candidate', function ($query) use ($mindate){

Programming Language : PHP , Popularity : 5/10

laravel tinker factory

Not null laravel migration, phpmyadmin delete wordpress shortcode, php change version linux, regex for email php, php get pc cpu gpu, memory etc uses all information example, string to bool php, call php function in js, php pdo rowcount, how to get the current date in php, object of class datetime could not be converted to string, xml to object php, how does substr_compare() works php, php to save txt html.

DEV Community

DEV Community

Zubair Mohsin

Posted on Feb 20, 2020 • Updated on Jan 27, 2021

Understanding Mass Assignment in Laravel Eloquent ORM

Laravel Eloquent ORM provides a simple API to work with database. It is an implementation of Active Record pattern. Each database table is mapped to a Model class which is used for interacting with that table.

Mass Assignment

Let's break down this word.

  • Mass means large number
  • Assignment means the assignment operator in programming

In order to make developers life easier, Eloquent ORM offers Mass Assignment functionality which helps them assign (insert) large number of input to database.

Life, without Mass Assignment 😩

Let's consider that there is a form with 10 fields of user information.

and our Controller's store method looks like:

We are assigning each input manually to our model and then saving to database.

What if there was a way to insert all the coming input without the manual assignment?

Life, with Mass Assignment 🥳

Laravel Eloquent ORM provides a create method which helps you save all the input with single line.

How cool is that, right? 🤓 With single line we are saving all input to database. In future, if we add more input fields in our HTML form, we don't need to worry about our saving to database part.

Input fields name attribute must match the column name in our database.

Potential Vulnerability

For the sake of understanding, let's consider that we have an is_admin column on users table with true / false value.

A malicious user can inject their own HTML, a hidden input as below:

With Mass Assignment, is_admin will be assigned true and the user will have Admin rights on website, which we don't want 😡

Avoiding the vulnerability

There are two ways to handle this.

  • We can specify (whitelist) which columns can be mass assigned.

Laravel Eloquent provides an easy way to achieve this. In your model class, add $fillable property and specify names of columns in the array like below:

Any input field other than these passed to create() method will throw MassAssignmentException .

  • We can specify ( blacklist ) which columns cannot be mass assigned.

You can achieve this by adding $guarded property in model class:

All columns other than is_admin will now be mass assignable.

You can either choose $fillable or $guarded but not both.

So there you have it. Happy Mass Assigning with Laravel Eloquent 🥳 👨🏽‍💻

Top comments (7)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

mazentouati profile image

  • Location The Netherlands
  • Education Media Engineering Master's degree
  • Work Back-end developer
  • Joined Nov 6, 2018

Great breakdown I would like to add these extra tips:

If all of your table fields are fillable you should consider using protected $guarded = []

You can use $request->only(array $fields) to pick only certain columns.

Assuming you're using Laravel form request ( learn more here ) you can simply use $request->validated() to get the validated data.

PS: for tip 2 & 3 you probably should opt for protected $guarded = []

zubairmohsin33 profile image

  • Email [email protected]
  • Location Lahore, Pakistan
  • Education BS(Computer Sciences)
  • Work Engineering Lead at ThePacketHub
  • Joined Mar 4, 2019

Hey thank you so much for sharing these tips. There are multiple ways to achieve the same objective. To get better understanding, I kept the options minimal.

roelofjanelsinga profile image

  • Email [email protected]
  • Location Groningen, The Netherlands
  • Education Hanzehogeschool Groningen
  • Work Owner of Plant care for Beginners
  • Joined Aug 26, 2019

I've used Laravel professionally for 5 years and even though I assumed this is how it worked, I learned something new here! Great post, thank you for this!

Awesome :) Glad you liked it.

wakeupneo47 profile image

  • Location Turkey
  • Work Laravel Developer
  • Joined Feb 23, 2021

Great job , great explanation.

victorallen22 profile image

  • Location Nairobi, Kenya
  • Joined Sep 21, 2017

Very well put...you got me sorted! Thanks for sharing 👍

ypaatil profile image

  • Joined Oct 1, 2021

Great job. You are cleared my concept.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

emcf profile image

How to use OpenAI’s new Structured Outputs API (with code)

Emmett McFarlane - Aug 9

nullvoidkage profile image

📝 Angular Cheat Sheet for Developers

Nikko Ferwelo - Aug 22

techalgospotlight profile image

Top 15 HTML Elements You Should Know in 2024

TechAlgoSpotlight - Aug 28

jessalejo profile image

Create a New Rails 7.2 Project with Bootstrap Theme on a Newly Set Up WSL (in Minutes)

Jess Alejo - Aug 10

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Amit Merchant Verified ($10/year for the domain)

A blog on PHP, JavaScript, and more

Allow mass assignment for all the models in Laravel

November 20, 2021 · Laravel

While it’s not recommended to allow all of your model’s attributes mass assignable since in that case you need to make sure to hand-craft the arrays passed to Eloquent’s fill , create , and update methods.

But there might be some instances where you may want to consider unguarding all of the attributes.

The de-facto way of unguarding a single model is to set an empty array to the $guarded property like so.

But what if you want to make all of your models as mass assignable all at once ? How would you do that?

Well, to do that, you need to use the unguard() method on the Illuminate\Database\Eloquent\Model class. This can be done in the boot method of the applications’s AppServiceProvider like so.

That’s it! This will make all your models mass assignable from a single place.

PHP 8 in a Nutshell book cover

» Share: Twitter , Facebook , Hacker News

Like this article? Consider leaving a

Caricature of Amit Merchant sketched by a friend

👋 Hi there! I'm Amit . I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

More on similar topics

Keeping a check on queries in Laravel

Request fingerprints and how to use them in Laravel

Separating Database Hosts to Optimize Read and Write Operations in Laravel

Using Generics in Laravel Eloquent

Awesome Sponsors

Download my eBook

allow mass assignment laravel

Get the latest articles delivered right to your inbox!

No spam guaranteed.

Follow me everywhere

More in "Laravel"

Advanced Markdown using Extensions in Laravel

Recently Published

Enabling Richer PWA Install UI on Desktop NEW

Using Human-friendly dates in Git

Popover API 101

Top Categories

Mass Assignment Vulnerabilities and Validation in Laravel

driesvints, elkdev liked this article

Introduction

The following article is an excerpt from my ebook Battle Ready Laravel , which is a guide to auditing, testing, fixing, and improving your Laravel applications.

Validation is a really important part of any web application and can help strengthen your app's security. But, it's also something that is often ignored or forgotten about (at least on the projects that I've audited and been brought on board to work on).

In this article, we're going to briefly look at different things to look out for when auditing your app's security, or adding new validation. We'll also look at how you can use " Enlightn " to detect potential mass assignment vulnerabilities.

Mass Assignment Analysis with Enlightn

What is enlightn.

A great tool that we can use to get insight into our project is Enlightn .

Enlightn is a CLI (command-line interface) application that you can run to get recommendations about how to improve the performance and security of your Laravel projects. Not only does it provide some static analysis tooling, it also performs dynamic analysis using tooling that was built specifically to analyse Laravel projects. So the results that it generates can be incredibly useful.

At the time of writing, Enlightn offers a free version and paid versions. The free version offers 64 checks, whereas the paid versions offer 128 checks.

One useful thing about Enlightn is that you can install it on your production servers (which is recommended by the official documentation) as well as your development environment. It doesn't incur any overhead on your application, so it shouldn't affect your project's performance and can provide additional analysis into your server's configuration.

Using the Mass Assignment Analyzer

One of the useful analysis that Enlightn performs is the "Mass Assignment Analyzer". It scans through your application's code to find potential mass assignment vulnerabilities.

Mass assignment vulnerabilities can be exploited by malicious users to change the state of data in your database that isn't meant to be changed. To understand this issue, let's take a quick look at a potential vulnerability that I have come across in projects in the past.

Assume that we have a User model that has several fields: id , name , email , password , is_admin , created_at , and updated_at .

Imagine our project's user interface has a form a user can use to update the user. The form only has two fields: name and password . The controller method to handle this form and update the user might like something like the following:

The code above would work , however it would be susceptible to being exploited. For example, if a malicious user tried passing an is_admin field in the request body, they would be able to change a field that wasn't supposed to be able to be changed. In this particular case, this could lead to a permission escalation vulnerability that would allow a non-admin to make themselves an admin. As you can imagine, this could cause data protection issues and could lead to user data being leaked.

The Enlightn documentation provides several examples of the types of mass assignment usages it can detect:

It's important to remember that this becomes less of an issue if you have the $fillable field defined on your models. For example, if we wanted to state that only the name and email fields could be updated when mass assigning values, we could update the user model to look like so:

This would mean that if a malicious user was to pass the is_admin field in the request, it would be ignored when trying to assign the value to the User model.

However, I would recommend completely avoiding using the all method when mass assigning and only ever use the validated , safe , or only methods on the Request . By doing this, you can always have confidence that you explicitly defined the fields that you're assigning. For example, if we wanted to update our controller to use only , it may look something like this:

If we want to update our code to use the validated or safe methods, we'll first want to create a form request class. In this example, we'll create a UpdateUserRequest :

We can change our controller method to use the form request by type hinting it in the update method's signature and use the validated method:

Alternatively, we can also use the safe method like so:

Checking Validation

When auditing your application, you'll want to check through each of your controller methods to ensure that the request data is correctly validated. As we've already covered in the Mass Assignment Analysis example that Enlightn provides, we know that all data that is used in our controller should be validated and that we should never trust data provided by a user.

Whenever you're checking a controller, you must ask yourself " Am I sure that this request data has been validated and is safe to store? ". As we briefly covered earlier, it's important to remember that client-side validation isn't a substitute for server-side validation; both should be used together. For example, in past projects I have seen no server-side validation for "date" fields because the form provides a date picker, so the original developer thought that this would be enough to deter users from sending any other data than a date. As a result, this meant that different types of data could be passed to this field that could potentially be stored in the database (either by mistake or maliciously).

Applying the Basic Rules

When validating a field, I try to apply these four types of rules as a bare minimum:

  • Is the field required? - Are we expecting this field to always be present in the request? If so, we can apply the required rule. If not, we can use the nullable or sometimes rule.
  • What data type is the field? - Are we expecting an email, string, integer, boolean, or file? If so, we can apply email , string , integer , boolean or files rules.
  • Is there a minimum value (or length) this field can be? - For example, if we were adding a price filter for a product listing page, we wouldn't want to allow a user to set the price range to -1 and would want it to go no lower than 0.
  • Is there a maximum field (or length) this field can be? - For example, if we have a "create" form for a product page, we might not want the titles to be any longer than 100 characters.

So you can think of your validation rules as being written using the following format:

By applying these rules, not only can it add some basic standard for your security measures, it can also improve the readability of the code and the quality of submitted data.

For example, let's assume that we have these fields in a request:

Although you might be able to guess what these fields are and their data types, you probably wouldn't be able to answer the 4 questions above for each one. However, if we were to apply the four questions to these fields and apply the necessary rules, the fields might look like so in our request:

Now that we've added these rules, we have more information about the four fields in our request and what to expect when working with them in our controllers. This can make development much easier for users that work on the code after you because they can have a clearer understanding of what the request contains.

Applying these four questions to all of your request fields can be extremely valuable. If you find any requests that don't already have this validation, or if you find any fields in a request missing any of these rules, I'd recommend adding them. But it's worth noting that these are only a bare minimum and that in a majority of cases you'll want to use extra rules to ensure more safety.

Checking for Empty Validation

An issue I've found quite often with projects that I have audited is the use of empty rules for validating a field. To understand this a little better, let's take a look at a basic example of a controller that is storing a user in the database:

The store method in the UserController is taking the validated data (in this case, the name and email ), creating a user with them, then returning a redirect response to the users 'show' page. There isn't any problem with this so far.

However, let's say that this was originally written several months ago and that we now want to add a new twitter_handle field. In some projects that I have audited, I have come across fields added to the validation but without any rules applied like so:

This means that the twitter_handle field can now be passed in the request and stored. This can be a dangerous move because it circumvents the purpose of validating the data before it is stored.

It is possible that the developer did this so that they could build the feature quickly and then forgot to add the rules before committing their code. It may also be possible that the developer didn't think it was necessary. However, as we've covered, all data should be validated on the server-side so that we're always sure the data we're working with is acceptable.

If you come across empty validation rule sets like this, you will likely want to add the rules to make sure the field is covered. You may also want to check the database to ensure that no invalid data has been stored.

Hopefully, this post should have given you a brief insight into some of the things to look for when auditing your Laravel application's validation.

If you enjoyed reading this post, I'd love to hear about it. Likewise, if you have any feedback to improve the future ones, I'd also love to hear that too.

You might also be interested in checking out my 220+ page ebook " Battle Ready Laravel " which covers similar topics in more depth.

If you're interested in getting updated each time I publish a new post, feel free to sign up for my newsletter .

Keep on building awesome stuff! 🚀

Other articles you might like

Find outdated composer dependencies using "composer outdated".

Introduction When building your PHP web applications, it's important to keep your dependencies up-to...

PHP 8.4 Property Hooks

Introduction PHP 8.4 will be released in November 2024 and will be bringing a cool new feature: prop...

New Array Functions in PHP 8.4

Introduction PHP 8.4 is set to be released in November 2024 and will introduce some handy new array...

We'd like to thank these amazing companies for supporting us

Fathom

Your logo here?

The Laravel portal for problem solving, knowledge sharing and community building.

The community

Laravel

Unsupported browser

This site was designed for modern browsers and tested with Internet Explorer version 10 and later.

It may not look or work correctly on your browser.

Get Started With Laravel 8

Jeremy McPeak

Next lesson playing in 5 seconds

4.6 using mass assignment.

We can use mass assignment to easily create and update records in the database. It is dangerous, however, so in this lesson I'll teach you how to use mass assignment safely.

1. Introduction 2 lessons, 07:30

1.1 introduction 01:53, 1.2 set up your environment 05:37, 2. basic routing 5 lessons, 40:40, 2.1 routing requests 07:07, 2.2 working with query data 09:37, 2.3 route url parameters 07:24, 2.4 routing to controllers 08:22, 2.5 creating a view 08:10, 3. the blade templating engine 7 lessons, 45:30, 3.1 introducing layouts 08:15, 3.2 working with static resources 05:03, 3.3 generating urls for routes 03:26, 3.4 organizing views 09:41, 3.5 using blade directives 07:37, 3.6 showing and linking data 07:31, 3.7 setting up the database 03:57, 4. working with data 6 lessons, 48:45, 4.1 creating migrations and models 10:08, 4.2 saving database records 08:57, 4.3 validating user input 07:38, 4.4 updating data 07:04, 4.5 using type hints and request classes 08:50, 4.6 using mass assignment 06:08, 5. conclusion 1 lesson, 01:03, 5.1 conclusion 01:03.

We can also use mass assignment to clean up and simplify our code. There are, however, some issues that we will need to discuss. But, first, what is mass assignment? Well, whenever we have created or updated a record in the database, we have done so by assigning the columns individually. We are being very explicit as to what we are setting and then we are saving that record, that is individual assignment. Mass assignment is doing all those things, all at once. So, the code to do so would look like this. In order to create a record, we would use our modal class. It has a method called Create, and then we would just pass in the data that we needed to create that record. And that's it, we no longer have to set name, brand, year made, or saved, or anything like that. This one line of code will do all that for us. And the same is true for update. So if we look at the update method, we still need to use our record object that we have in this guitar variable, but we would call an update method. We would, once again, pass in the data that we wanted to update, and that's it. Everything else is done for us. That is mass assignment. So, the first thing about mass assignment is that the data that we are passing to either the update method or the create method needs to have keys that are the same names as the columns in the database. Like, for example, we have name in the database, but our form has guitar-name. The database has year_made and the form has just year. So, in order to use mass assignment, we need to change the field names in our forms so that they match the column names. That's not that big of a deal, so, we can go ahead and do that. Now, as you're doing this, don't forget to change the values of the four attributes for the appropriate labels. That was for the year made. Well, it's now year made, and for the name. Let's do the same thing inside of the edit view. And we also need to change the guitar form request class because we used these form field names there. And we did so, really, in two places. If we look at the rules, we need to modify those field names so that we have name and then year made. But when it comes to prepare for validation, we need to do the same thing. Now, since we just have a name property, now we can use the property syntax and then we will change year made. We also need to change the keys here to match, but that's going to make everything work. So with these changes in place, we should be able to create and update these records. So let's go ahead and let's try that. Let's go to the Create form. And let's add a Strat, because we don't have one, yet. The brand is Fender, and the year made, let's just do 2021. And whenever we submit this, we are going to get an error. And it says, add a name to fillable property to allow mass assignment. So, here's the thing about mass assignment, it's very dangerous. You are taking the request data. And even though we are validating it, which is very good, but we are just kind of blindly passing that onto the update and the create methods. Saying, here database, take this information and create or update a record. And that's really not a big deal for the data that we are working with, but imagine that you are building a system that is working with some sensitive information like user accounts. And while you are validating that information, you aren't really checking everything. Maybe the users supplied some extra fields in the request that would then be populated in the database, if there was a matching column name. There's a lot of things that can go wrong with mass mssignment. So it is something that we have to opt into. And if we look at this message, again, it says add name to fillable property. So what this means is, we go to our guitar model and we are going to add a property, it's a protected property called fillable. And this is, simply, an array that contains the columns that are okay to mass assign. In our case, that's just about every one of them. So that means name, brand, and year made. But if we left any one of these off, then eloquent will not allow that column to be assigned to value using mass assignment. We would have to do so explicitly, like we did before, by assigning a value to that column. But, as I said, the data that we are working with is okay to mass assign. There's nothing sensitive, nothing that's going to break or cause some kind of vulnerability within our application. So, now, we can go back. Let's refresh and we'll just hit Continue here, so that it will resubmit that form. And then everything should work. We should see our list of guitars, and here we can see the Strat that we added. And, of course, if we wanted to test the editing of that, all we have to do is go to the edit form for that guitar, let's add edited to the name and then we will submit. And, once again, we're going to see that that works. Because now that we sent that fillable property in our guitar model, this works for creating and updating. It's a one-time set thing. So there's nothing wrong with using Mass Assignment, just be very careful when you do so. If there are columns in your database that control how the application behaves or controls a user's access to certain parts of your application, don't make those columns fillable. It adds a little extra work on your part, but it makes your code much safer.

Jeremy McPeak

Fix : Add [_token] to fillable property to allow mass assignment Laravel

Photo of tgugnani

Mar 8, 2021

If you are working with Laravel and you encounter the following error while creating a new record in the database using Laravel Models

Add [_token] to fillable property to allow mass assignment on [App\Models\Post].

A mass assignment exception is usually caused because you didn't specify the fillable (or guarded the opposite) attributes in your model. Do this:

This way you also don't have to worry about _token because only the specified fields will be filled and saved in the db no matter what other stuff you pass to the model.

  • General Solutions
  • Ruby On Rails
  • Jackson (JSON Object Mapper)
  • GSON (JSON Object Mapper)
  • JSON-Lib (JSON Object Mapper)
  • Flexjson (JSON Object Mapper)
  • References and future reading
  • Microservices Security
  • Microservices based Security Arch Doc
  • Mobile Application Security
  • Multifactor Authentication
  • NPM Security
  • Network Segmentation
  • NodeJS Docker
  • Nodejs Security
  • OS Command Injection Defense
  • PHP Configuration
  • Password Storage
  • Prototype Pollution Prevention
  • Query Parameterization
  • REST Assessment
  • REST Security
  • Ruby on Rails
  • SAML Security
  • SQL Injection Prevention
  • Secrets Management
  • Secure Cloud Architecture
  • Secure Product Design
  • Securing Cascading Style Sheets
  • Server Side Request Forgery Prevention
  • Session Management
  • Software Supply Chain Security.md
  • TLS Cipher String
  • Third Party Javascript Management
  • Threat Modeling
  • Transaction Authorization
  • Transport Layer Protection
  • Transport Layer Security
  • Unvalidated Redirects and Forwards
  • User Privacy Protection
  • Virtual Patching
  • Vulnerability Disclosure
  • Vulnerable Dependency Management
  • Web Service Security
  • XML External Entity Prevention
  • XML Security
  • XSS Filter Evasion

Mass Assignment Cheat Sheet ¶

Introduction ¶, definition ¶.

Software frameworks sometime allow developers to automatically bind HTTP request parameters into program code variables or objects to make using that framework easier on developers. This can sometimes cause harm.

Attackers can sometimes use this methodology to create new parameters that the developer never intended which in turn creates or overwrites new variable or objects in program code that was not intended.

This is called a Mass Assignment vulnerability.

Alternative Names ¶

Depending on the language/framework in question, this vulnerability can have several alternative names :

  • Mass Assignment: Ruby on Rails, NodeJS.
  • Autobinding: Spring MVC, ASP NET MVC.
  • Object injection: PHP.

Example ¶

Suppose there is a form for editing a user's account information:

Here is the object that the form is binding to:

Here is the controller handling the request:

Here is the typical request:

And here is the exploit in which we set the value of the attribute isAdmin of the instance of the class User :

Exploitability ¶

This functionality becomes exploitable when:

  • Attacker can guess common sensitive fields.
  • Attacker has access to source code and can review the models for sensitive fields.
  • AND the object with sensitive fields has an empty constructor.

GitHub case study ¶

In 2012, GitHub was hacked using mass assignment. A user was able to upload his public key to any organization and thus make any subsequent changes in their repositories. GitHub's Blog Post .

Solutions ¶

  • Allow-list the bindable, non-sensitive fields.
  • Block-list the non-bindable, sensitive fields.
  • Use Data Transfer Objects (DTOs).

General Solutions ¶

An architectural approach is to create Data Transfer Objects and avoid binding input directly to domain objects. Only the fields that are meant to be editable by the user are included in the DTO.

Language & Framework specific solutions ¶

Spring mvc ¶, allow-listing ¶.

Take a look here for the documentation.

Block-listing ¶

Nodejs + mongoose ¶, ruby on rails ¶, django ¶, asp net ¶, php laravel + eloquent ¶, grails ¶, play ¶, jackson (json object mapper) ¶.

Take a look here and here for the documentation.

GSON (JSON Object Mapper) ¶

Take a look here and here for the document.

JSON-Lib (JSON Object Mapper) ¶

Flexjson (json object mapper) ¶, references and future reading ¶.

  • Mass Assignment, Rails and You
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Best way to handle additional fields in mass assignment in Laravel?

App\Models\Venue:

StoreVenueRequest (rules part):

VenueController - store() method:

Тhe code works perfectly, but I'm not sure this is the best way. Is there a way to avoid these two lines, mostly second one:

The only thing I can think of is hidden input field in the form with authenticated user id. I'm looking for the best way.

MorganFreeFarm's user avatar

  • @lagbox But it looks more like a hack, instead of Laravel way –  MorganFreeFarm Commented Jan 6, 2022 at 17:02

You could merge an array with the $validated array:

This is the same as moving it to the assignment of $validated :

No matter what you would have to merge arrays in some way before this point or at this point if you want this to be done with mass assignment. Otherwise you will be setting individual elements of an array, like you currently are doing.

lagbox's user avatar

  • @TimLewis stackoverflow.com/questions/70320201/… adjusting the validators data from inside the FormRequest –  lagbox Commented Jan 6, 2022 at 18:36

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged php laravel laravel-8 or ask your own question .

  • The Overflow Blog
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Is 3 ohm resistance value of a PCB fuse reasonable?
  • Equation for the Logarithmic Spiral from a vertex to the Brocard Point
  • What counts as the Earth's mass? At which point would it increase or decrease?
  • World Building Knowledgebase - How to write good Military World Building
  • Took a pic of old school friend in the 80s who is now quite famous and written a huge selling memoir. Pic has ben used in book without permission
  • Indicator function necessary for independence from filtration?
  • How much easier/harder would it be to colonize space if humans found a method of giving ourselves bodies that could survive in almost anything?
  • QGIS: Connect to the mActionDigitizeWithCurve map tool toggled signal
  • Is there a way to define a function over the complex numbers, that satisfies a log property?
  • Why are IC and IE different? Aren't the two 1k ohm resistors in series and thus the current through them should be the same?
  • Getting home JUST before tzeit chochavim, in the time frame of Bein hashmashot---Shabbos violation or not?
  • Is a company liable for "potential" harms?
  • Does a held action have to be an action?
  • Why is Namibia killing game animals for food rather than allowing more big game hunting?
  • Should you refactor when there are no tests?
  • My supervisor wants me to switch to another software/programming language that I am not proficient in. What to do?
  • A SF novel where one character makes a "light portrait" of another one, with huge consequences
  • Jewelry and adornment
  • Strong Completenss vs Finitely Strong Completenss
  • Problem with closest_point_on_mesh when the closest point is on an edge
  • Functor composition rule necessary?
  • Can you use 'sollen' the same way as 'should' in sentences about possibility that something happens?
  • Seinfeldisms in O.R
  • If I was knocked approximately 1500 feet into the air and I can fly, could I perform a sort of 'Terminal Velocity Tackle'?

allow mass assignment laravel

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MassAssignmentException #28743

@walker007

walker007 commented Jun 5, 2019 • edited Loading

Tipo_evento.php

App; use Illuminate\Database\Eloquent\Model; class Tipo_evento extends Model { protected $fillables = [ 'nome','description' ]; }

Create.blade.php

('template') @section('title') Criar novo tipo de evento @endsection @section('content') {{ Form::open(['route' => ['editar.tipo.evento.save'], 'method'=>'post']) }} @include('evento.tipos.form') //include form on evento/tipo/form.blade.php {{ Form::close() }} @endsection

web.php

::get('criar/tipodevento',['as'=>'novo.tipo.evento', 'uses'=>'TipoEventoController@novoTipo']); Route::post('salvar/novo/tipo',['as'=>'editar.tipo.evento.save', 'uses'=>'TipoEventoController@saveTipo']);

TipoEventoController.php

function saveTipo(Request $request) { $salvar = $this->Tipo_evento::create($request->all()); if ($salvar) { //Gera a notificação session()->flash('notify', ['title' => 'Tipo de evento Cadastrado', 'type' => 'success', 'message' => 'O tipo de evento foi cadastrado com sucesso']); //Redireciona para a home return redirect()->route('tipo.evento'); }else{ session()->flash('notify', ['title' => 'Tipo de evento não foi cadastrado', 'type' => 'error', 'message' => 'o tipo de evento não foi cadastrado, verifique os dados e tente novamente']); //Redireciona para a home return redirect()->route('equipe.edit',$request->equipe_id); } }

The laravel try to create data with the input _token and _method

@staudenmeir

staudenmeir commented Jun 5, 2019

It's , not :

Tipo_evento extends Model { protected $fillable = [ 'nome','description' ]; }

Sorry, something went wrong.

walker007 commented Jun 5, 2019

, not :

oh thanks :)

@laurencei

No branches or pull requests

@laurencei

IMAGES

  1. Laravel mass assignment and fillable vs guarded

    allow mass assignment laravel

  2. Allow mass assignment for all the models in Laravel

    allow mass assignment laravel

  3. Laravel 10 full course for beginner

    allow mass assignment laravel

  4. Laravel Eloquent Tips

    allow mass assignment laravel

  5. Laravel Mass Assignment: Fillable or Guarded?

    allow mass assignment laravel

  6. Laravel Basics

    allow mass assignment laravel

VIDEO

  1. Tutorial Laravel 10 untuk Pemula #6 : Menampilkan Detail Data By ID

  2. Roles And Permissions Using Laratrust Laravel

  3. Laracasts Laravel

  4. Digital Storytelling

  5. Laravel Lab :Mass Assignment , Eloquent Relationship .Part 2

  6. Exploiting a mass assignment vulnerability

COMMENTS

  1. Add [title] to fillable property to allow mass assignment on [App\Post]

    I was looking at it trying to understand why it didn't like "image_url", screaming "Add ['image_url'] to fillable property to allow mass assignment". I realized that I added the ->first() to make sure I was only getting one post, but since all slugs are validated and verified to be unique, I dropped the ->first() .

  2. What does "Mass Assignment" mean in Laravel?

    39. Mass assignment is a process of sending an array of data that will be saved to the specified model at once. In general, you don't need to save data on your model on one by one basis, but rather in a single process. Mass assignment is good, but there are certain security problems behind it.

  3. Laravel

    Laravel offers several methods that allow you to configure Eloquent's behavior and "strictness" in a variety of situations. ... To learn more about mass assignment, please consult the mass assignment documentation. Updates. The save method may also be used to update models that already exist in the database. To update a model, you should ...

  4. Add [title] to fillable property to allow mass assignment on [App

    This demonstrates how you can add a title field to the fillable property in the Post model in Laravel and use mass assignment to set the title field when creating or updating Post instances. Solution 2: Explanation: ... To allow mass assignment on a specific model, you need to explicitly specify which attributes can be mass assigned. ...

  5. Add [name] to fillable property to allow mass assignment on

    Add [name] to fillable property to allow mass assignment on. ... This series is all about building practical features for typical Laravel web application. Charts, stats, and image uploaders are just a few examples that we'll be reviewing together. We'll also leverage various JavaScript libraries whenever we require additional interactivity for ...

  6. Add [_token] to fillable property to allow mass assignment

    Add [_token] to fillable property to allow mass assignment

  7. Laravel101: The Role of Mass Assignment in Eloquent Model

    Laravel wants to ensure you're aware of this potential issue. Luckily, we have two solutions to change this default behavior. One solution is to use the fillable property, which is an array of fields that you want to allow for mass assignment

  8. Understanding Mass Assignment in Laravel Eloquent ORM

    Laravel Eloquent ORM provides a simple API to work with database. It is an implementation of Active Record pattern. Each database table is mapped to a Model class which is used for interacting with that table.. Mass Assignment Let's break down this word. Mass means large number; Assignment means the assignment operator in programming; In order to make developers life easier, Eloquent ORM ...

  9. What is Laravel Mass Assignment?

    To allow mass assignments Laravel provides you with two properties, fillable and guarded. They act as a whitelist and blacklist respectively. You only use one or the other in each model, never both in the same model. Read the more in-depth full article at https://codestation.io with code examples. Laravel. Programming.

  10. What Does "Mass Assignment" Mean in Laravel?

    Mass assignment in Laravel is a powerful feature that simplifies working with models and database records. By allowing multiple attribute assignments in a single operation, developers can save ...

  11. laravel

    Marking properties as fillable when using Laravel relationship functions 2 "Add [name] to fillable property to allow mass assignment on [Illuminate\Foundation\Auth\User]."

  12. Allow mass assignment for all the models in Laravel

    Allow mass assignment for all the models in Laravel November 20, 2021 · Laravel While it's not recommended to allow all of your model's attributes mass assignable since in that case you need to make sure to hand-craft the arrays passed to Eloquent's fill , create , and update methods.

  13. Add [title] to fillable property to allow mass assignment on [App\Post]

    Push your web development skills to the next level, through expert screencasts on PHP, Laravel, Vue, and much more. Get Started For Free! Want us to email you occasionally with Laracasts news?

  14. Mass Assignment Vulnerabilities and Validation in Laravel

    Using the Mass Assignment Analyzer. One of the useful analysis that Enlightn performs is the "Mass Assignment Analyzer". It scans through your application's code to find potential mass assignment vulnerabilities. Mass assignment vulnerabilities can be exploited by malicious users to change the state of data in your database that isn't meant to ...

  15. Get Started With Laravel 8

    Since Professional Ajax, 1st Edition, I've been blessed to take part in other book projects: Professional Ajax 2nd Edition, and Beginning JavaScript 3rd and 4th editions. We can use mass assignment to easily create and update records in the database. It is dangerous, however, so in this lesson I'll teach you how to use mass assignment safely.

  16. Fix : Add [_token] to fillable property to allow mass assignment Laravel

    Fix : Add [_token] to fillable property to allow mass assignment Laravel Laravel tgugnani. Mar 8, 2021 ... Add [_token] to fillable property to allow mass assignment on [App\Models\Post]. A mass assignment exception is usually caused because you didn't specify the fillable (or guarded the opposite) attributes in your model. Do this:

  17. php

    Warning : be careful when you allow the mass assignment of critical fields like password or role. It could lead to a security issue because users could be able to update this fields values when you don't want to.

  18. Mass Assignment

    This is called a Mass Assignment vulnerability. Alternative Names¶ Depending on the language/framework in question, this vulnerability can have several alternative names: Mass Assignment: Ruby on Rails, NodeJS. Autobinding: Spring MVC, ASP NET MVC. Object injection: PHP. Example¶ Suppose there is a form for editing a user's account information:

  19. Add [title] to fillable property to allow mass assignment on [App\Post]

    Arguments "Add [title] to fillable property to allow mass assignment on [App\\Post]." Laracasts Elite. Hall of Fame. Snapey. Posted 6 years ago. Best Answer . Community Pillar. ... What's New in Laravel 10. It's a new year, and that means we also get a new major release of Laravel! As of February 14th, 2023, Laravel has now officially bumped to ...

  20. Best way to handle additional fields in mass assignment in Laravel?

    laravel mass assignment with extra field. 0. How can I use mass assignment together with two model? Hot Network Questions Why is the tortoise associated with 人情? What are the 270 mitzvot relevant today? AM-GM inequality (but equality cannot be attained) Is this screw inside a 2-prong receptacle a possible ground? ...

  21. MassAssignmentException · Issue #28743 · laravel/framework

    Laravel Version: 5.8 PHP Version: 7.3 Description: Add [_token] to fillable property to allow mass assignment on [App\Tipo_evento]. Tipo_evento.php namespace App; use Illuminate\Database\Eloquent\Model; class Tipo_evento extends Model { ...