Laravel Mass Assignment Fillable Calendar

Last week I looked at setting up a basic invitation system in Laravel 4. I looked at creating the table, the model and the repository and I showed you how to very easily create a new invitation and check for valid invitations when a new user tries to sign up for your application.

This basic foundation has put the right components together, but there is still quite a bit missing from the system to make it robust and capable of meeting all of my requirements.

In this week’s tutorial I’m going to look at building on top of last week’s foundation. In today’s tutorial I’ll be looking at:

  1. Automatically generating the invitation code
  2. Validation through a service class
  3. A filter to protect the registration route

Automatically generating the invitation code

The first thing I will do is to clean up how the invitation code is generated. You might remember from last time that I was creating the code in the method of the . This did the job but it wasn’t ideal.

The invitation code should be generated only when the new invitation is created. This means it will never have to be updated so we don’t need to pollute any of the other code with references to it. Instead, the code should just be generated for us.

Fortunately, Eloquent fires events that allow you to hook on to the various stages of the model’s lifecycle. This means we can write code that should be run based upon what the model is doing.

You can read more about the Eloquent’s Model Events and what you have available to you in the documentation.

In this situation, I want to hook on to the event to automatically generate the invitation code before the model is saved.

The first thing to do is to remove the from the array in the model. This will prevent the code from ever being mass-assigned:

Next I need to override the static method to register my event:

First you need to call the method on the parent class.

Next you can call the event method and pass in a closure. In this example, I’m calling the method.

The closure accepts an instance of the . I will then call the method so I don’t end up with lots of code in this closure.

Finally, my looks like this:

As you can see, I simply set the randomly generated code to the property. There’s no need to call the method as this will automatically called as part of the model’s lifecycle.

Now I can clean up the method on the as the code will be automatically generated:

Validation through a service class

One of the problems of the implementation from last week was, there was no validation to prevent someone from requesting multiple invites for the same email address.

In order to ensure that Cribbb will only accept valid data I need to insert a layer of validation before the invitation is created.

If you remember back to Advanced Validation as a Service for Laravel 4, I’ve already got a foundation for creating validation classes in place.

However, should this go in the Controller? Or in the Repository? Or somewhere else?

In this instance I’m going to create a new service class for creating invitations. The reason for this is, I’m going to need to have different ways of creating invitations, and so separating the logic into it’s own class makes more sense than trying to crowbar it into the repository or duplicating my efforts in the controller.

The invitation classes are their own component of Cribbb and so they deserve their own namespace. I’m going to keep all of these classes under the namespace.

The class I will create is for requesting a new invite. This class will be called .

Here is the basic outline for :

As you can see from the code above, I’m injecting the into this class and setting the instance as a class property. This means I no longer need to inject the repository into the controller.

I will also set up the property as a new instance of . I prefer this to be an empty instance of rather than setting it as because the class has a couple of nice public methods for working with an empty bag. You will also notice that I instantiate a new instance of inside the controller, rather than injecting it. This violates the dependency injection principle, but I think of the as an enhancement of the class, rather than a dependency, so I’m cool with that.

Next I need to create a validator class that will validate the request email address. Under I will create a new directory called to hold my validator classes.

To validate email addresses, I will use the following class:

If the above code doesn’t make sense, read my post on Advanced Validation as a Service for Laravel 4.

Now that I’ve got my validator class set up, I need to inject it into the class. Due to the evolving nature of this kind of code, I will inject my class as an array into the class. This means should I want to add more instances, I won’t have to modify the class.

My method now looks like this:

This might seem like an over-engineered solution, and for a lot of instances it probably is. If your class will never need to be modified for evolving business rules, then injecting the single class would be totally fine too.

Finally I can write the method that will actually create the new invitation:

First I spin through all of the validators and check that they are an instance of . If any one of the array values is not an instance of I will throw an . You could argue that the is a bit overkill, but I think for instances where we are accepting data into the application, it’s better to be safe than sorry.

Next I check that the meets the requirements of the rules of the validator. If it does not, I will add the errors to the class property.

Finally if there are no errors I will pass the data to the repository to create the new invitation.

The full class looks like this:

Injecting the service class into the Controller

Now that I’ve set up the service class I can inject it into the Controller to replace the injected repository:

As you can see from the code above, this is a simple switch-a-roo of the repository for the service class. However, now we don’t have any weird logic in the controller, and we can report errors back if the input data did not meet the requirements.

A filter to protect the registration route

Another problem the initial implementation had was protecting certain routes to only allow user’s with a valid invitation. This is required so I can limit who has access to the registration form.

In last week’s tutorial I simply checked for a valid invitation in the Controller method. This works, but it’s a kinda messy way of doing it. The valid invite check isn’t really the concern of the Controller method, and if I needed that same logic in another method on a different Controller I would have to duplicate my code.

Instead I can create a filter to ensure only users with a valid invitation are allowed to hit the route. If the user does not have a valid invitation I can just 404 the response because I can just pretend the registration route does not exist.

If you are new to Laravel filters, I would recommend that you also read How to use Laravel 4 Filters.

Here is my route filter:

First I check to see if the request has a parameter. If the request does not have a code, we can just bail out here.

Next I resolve an instance of the out of the IoC container. I then check to see if the code in the request is valid. If the code is not valid I can throw a 404 error.

Remember, a request is considered valid if the filter does not throw an exception or return a response.

Next in my I can delete the checking logic from last week and replace it with the :

Now if you try to hit the route, you should be returned a exception. Next, sign up with a valid email and grab the code from the database. Now if you try to hit you should be allowed to hit the method on the controller.


In part 1 of building an advanced invitation system, I looked at leveraging Eloquent’s event lifecycle to automatically generate invitation codes, and setting up a service class to deal with the logic of validating and creating a new invitation.

I think the thing to take away from this tutorial is, how much easier your life will be if you fence off bits of functionality so you don’t have to repeat yourself and you don’t have to rethink about how something should be implemented.

Generating the invitation codes should only happen when the invite is first created and should just be taken care for us just like the auto-incrementing id. None of the code for working with an invitation should need to know how to generate a code.

The question of should I put this in the Controller, the Repository or should I create a new Service class comes up often. My response is usually, “well, it depends”. In this example, I think you definitely do need a separate service class. In my case, there will be multiple ways for creating invitations in my application and the rules around what is considered “valid” data required for a new invitation is also likely to change. Hopefully this was a solid example of how to make the decision that you can use in your applications.

Over the next couple of weeks I will look at how existing users can invite new users, how to create a queue jump system and how to build a family tree that will record how new users were invited to the application.

This is a series of posts on building an entire Open Source application called Cribbb. All of the tutorials will be free to web, and all of the code is available on GitHub.

To view a full listing of the tutorials in this series, click here.

Eloquent: Getting Started


The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

Before getting started, be sure to configure a database connection in . For more information on configuring your database, check out the documentation.

Defining Models

To get started, let's create an Eloquent model. Models typically live in the directory, but you are free to place them anywhere that can be auto-loaded according to your file. All Eloquent models extend class.

The easiest way to create a model instance is using the Artisan command:

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

Eloquent Model Conventions

Now, let's look at an example model, which we will use to retrieve and store information from our database table:

Table Names

Note that we did not tell Eloquent which table to use for our 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 model stores records in the table. You may specify a custom table by defining a property on your model:

Primary Keys

Eloquent will also assume that each table has a primary key column named . You may define a protected property to override this convention.

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public property on your model to . If your primary key is not an integer, you should set the protected property on your model to .


By default, Eloquent expects and columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the property on your model to :

If you need to customize the format of your timestamps, set the 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 set the and constants in your model:

Database Connection

By default, all Eloquent models will use the default database connection configured for your application. If you would like to specify a different connection for the model, use the property:

Retrieving Models

Once you have created a model and its associated database table, you are ready to start retrieving data from your database. Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model. For example:

Adding Additional Constraints

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

{tip} Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.


For Eloquent methods like and which retrieve multiple results, an instance of will be returned. The class provides a variety of helpful methods for working with your Eloquent results:

Of course, you may also loop over the collection like an array:

Chunking Results

If you need to process thousands of Eloquent records, use the command. The method will retrieve a "chunk" of Eloquent models, feeding them to a given for processing. Using the method will conserve memory when working with large result sets:

The first argument passed to the method is the number of records you wish to receive per "chunk". The Closure passed as the second argument will be called 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.

Using Cursors

The method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the method may be used to greatly reduce your memory usage:

Retrieving Single Models / Aggregates

Of course, in addition to retrieving all of the records for a given table, you may also retrieve single records using or . Instead of returning a collection of models, these methods return a single model instance:

You may also call the method with an array of primary keys, which will return a collection of the matching records:

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 and methods will retrieve the first result of the query; however, if no result is found, a will be thrown:

If the exception is not caught, a HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return responses when using these methods:

Retrieving Aggregates

You may also use the , , , and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:

Inserting & Updating Models


To create a new record in the database, create a new model instance, set attributes on the model, then call the method:

In this example, we assign the parameter from the incoming HTTP request to the attribute of the model instance. When we call the method, a record will be inserted into the database. The and timestamps will automatically be set when the method is called, so there is no need to set them manually.


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

Mass Updates

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

The method expects an array of column and value pairs representing the columns that should be updated.

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

Mass Assignment

You may also use the method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a or attribute on the model, as all Eloquent models protect against mass-assignment by default.

A mass-assignment vulnerability occurs when a user passes an unexpected HTTP parameter through a request, and that parameter changes a column in your database you did not expect. For example, a malicious user might send an parameter through an HTTP request, which is then passed into your model's 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 property on the model. For example, let's make the attribute of our model mass assignable:

Once we have made the attributes mass assignable, we can use the method to insert a new record in the database. The method returns the saved model instance:

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

Guarding Attributes

While serves as a "white list" of attributes that should be mass assignable, you may also choose to use . The property should contain an array of attributes that you do not want to be mass assignable. All other attributes not in the array will be mass assignable. So, functions like a "black list". Of course, you should use either or - not both. In the example below, all attributes except for will be mass assignable:

If you would like to make all attributes mass assignable, you may define the property as an empty array:

Other Creation Methods


There are two other methods you may use to create models by mass assigning attributes: and . The 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 from the first parameter, along with those in the optional second parameter.

The method, like 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 has not yet been persisted to the database. You will need to call manually to persist it:

You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an method to do this in one step. Like the method, persists the model, so there's no need to call :

Deleting Models

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

Deleting An Existing Model By Key

In the example above, we are retrieving the model from the database before calling the method. However, if you know the primary key of the model, you may delete the model without retrieving it. To do so, call the method:

Deleting Models By Query

Of course, you may also run a delete statement on a set of models. In this example, we will delete all flights that are marked as inactive. Like mass updates, mass deletes will not fire any model events for the models that are deleted:

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

Soft Deleting

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 attribute is set on the model and inserted into the database. If a model has a non-null value, the model has been soft deleted. To enable soft deletes for a model, use the trait on the model and add the column to your property:

Of course, you should add the column to your database table. The Laravel schema builder contains a helper method to create this column:

Now, when you call the method on the model, the column will be set to the current date and time. And, 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, use the method:

Querying Soft Deleted Models

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 appear in a result set using the method on the query:

The method may also be used on a relationship query:

Retrieving Only Soft Deleted Models

The method will retrieve only soft deleted models:

Restoring Soft Deleted Models

Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model into an active state, use the method on a model instance:

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

Like the method, the method may also be used on relationships:

Permanently Deleting Models

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

Query Scopes

Global 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 pull "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.

Writing Global Scopes

Writing a global scope is simple. Define a class that implements the interface. This interface requires you to implement one method: . The method may add constraints to the query as needed:

{tip} If your global scope is adding columns to the select clause of the query, you should use the method instead of . 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 should override a given model's method and use the method:

After adding the scope, a query to will produce the following SQL:

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:

Removing Global Scopes

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

Or, if you defined the global scope using a Closure:

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

Local Scopes

Local scopes allow you to define common sets of 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 .

Scopes should always return a query builder instance:

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 prefix when calling the method. You can even chain calls to various scopes, for example:

Dynamic Scopes

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

Now, you may pass the parameters when calling the scope:


Eloquent models fire several events, allowing you to hook into the following points in a model's lifecycle: , , , , , , , , , , . Events allow you to easily execute code each time a specific model class is saved or updated in the database.

The event will fire when an existing model is retrieved from the database. When a new model is saved for the first time, the and events will fire. If a model already existed in the database and the method is called, the / events will fire. However, in both cases, the / events will fire.

To get started, define a property on your Eloquent model that maps various points of the Eloquent model's lifecycle to your own event classes:


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. Observers classes have method names which reflect the Eloquent events you wish to listen for. Each of these methods receives the model as their only argument. Laravel does not include a default directory for observers, so you may create any directory you like to house your observer classes:

To register an observer, use the method on the model you wish to observe. You may register observers in the method of one of your service providers. In this example, we'll register the observer in the :

0 Replies to “Laravel Mass Assignment Fillable Calendar”

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *