Laravel 5.3 Generate Key
- Laravel 5.8
- Laravel 7
- Laravel 5.3 Generate Key Generator
- Laravel Key Generate
- Laravel 5.3 Generate Key Code
- Before using Laravel's encrypter, you must set a key option in your config/app.php configuration file. You should use the php artisan key:generate command to generate this key since this Artisan command will use PHP's secure random bytes generator to build your key. If this value is not properly set, all values encrypted by Laravel will be.
- InfyOm laravel generator having lot many options available such as test cases generation, api parameters, soft delete, crud with datatables, model schema, custom table name, prefix option, generate from file or table and swagger laravel generator.
- Laravel アプリケーションキー(APPKEY)を設定する 2015年11月17日 2015年12月24日 @84kure ローカルのHomesteadで開発していたサイトをレンサバにアップしたらエラーになった。.
- Defining Models
- Retrieving Models
- Retrieving Single Models / Aggregates
- Inserting & Updating Models
- Deleting Models
- Query Scopes
- Events
Introduction
If you are starting fresh new laravel project, then boilerplates can be the best option for you to get started. It gives you a full laravel project with everything installed and published. It comes with easy steps to get boilerplate working. Clone AdminLTE a repo from: AdminLTE Boilerplate. That is correct! However, if you are using Laravel 5.3+, version 2.2 of Laravel-code-generator include five new commands to help you interact with migration from all folders. Check out the 'Command Changes' below for more info about the new commands. Previously Laravel-Code-Generator was limited to belongsTo type relation.
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 config/database.php. 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 app directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file. All Eloquent models extend IlluminateDatabaseEloquentModel class.
The easiest way to create a model instance is using the make:modelArtisan command:
If you would like to generate a database migration when you generate the model, you may use the --migration or -m option:
Eloquent Model Conventions
Now, let's look at an example Flight model, which we will use to retrieve and store information from our flights database table:
Table Names
Note that we did not tell Eloquent which table to use for 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. You may specify a custom table by defining a table property on your model:
Primary Keys
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey 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 automatically be cast to an int. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false:
If your primary key is not an integer, you should set the protected $keyType property on your model to string:
Timestamps
By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the $timestamps property on your model to false:
If you need to customize the format of your 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 set the CREATED_AT and UPDATED_AT 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 $connection property:
Default 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:
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 all 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 get 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.
Refreshing Models
You can refresh models 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:
Collections
For Eloquent methods like all and get which retrieve multiple results, an instance of IlluminateDatabaseEloquentCollection will be returned. The Collection class provides a variety of helpful methods for working with your Eloquent results:
You may also loop over the collection like an array:
Chunking Results
If you need to process thousands of Eloquent records, use the chunk command. The chunk method will retrieve a 'chunk' of Eloquent models, feeding them to a given Closure for processing. Using the chunk 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 cursor 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 cursor method may be used to greatly reduce your memory usage:
The cursor returns an IlluminateSupportLazyCollection instance. Lazy collections allow you to use many of collection methods available on typical Laravel collections while only loading a single model into memory at a time:
Advanced Subqueries
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 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. 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 query against the database:
Retrieving Single Models / Aggregates
In addition to retrieving all of the records for a given table, you may also retrieve single records using find, first, or firstWhere. Instead of returning a collection of models, these methods return a single model instance:
You may also call the find method with an array of primary keys, which will return a collection of the matching records:
Sometimes you may wish to retrieve the first result of a query or perform some other action if no results are found. The firstOr method will return the first result that is found or, if no results are found, execute the given callback. The result of the callback will be considered the result of the firstOr method:
The firstOr method also accepts an array of columns to retrieve:
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, a IlluminateDatabaseEloquentModelNotFoundException will be thrown:
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
Retrieving Aggregates
You may also use the count, sum, max, 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
Inserts
To create a new record in the database, create a new model instance, set attributes on the model, then call the save method:
In this example, we assign the name parameter from the incoming HTTP request to the name attribute of the AppFlight model instance. When we call the save method, a record will be inserted into the database. The 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.
Updates
The save 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 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 any number of 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.

{note} 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 they were originally loaded.
The isDirty method determines if any attributes have been changed since the model was loaded. You may pass a specific attribute name to determine if a particular attribute is dirty. The isClean method is the opposite of isDirty and 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. You may also pass an attribute name to see if a particular attribute was changed:
Mass Assignment
You may also use the create 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 fillable or guarded 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 is_admin parameter through an HTTP request, which is then passed into 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 we have made the attributes mass assignable, we can use the create method to insert a new record in the database. The create method returns the saved model instance:
If you already have a model instance, you may use the fill method to populate it with an array of attributes:
Guarding Attributes
While $fillable serves as a 'white list' of attributes that should be mass assignable, you may also choose to use $guarded. The $guarded 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, $guarded functions like a 'black list'. Importantly, you should use either $fillable or $guarded - not both. In the example below, all attributes except for price will be mass assignable:
If you would like to make all attributes mass assignable, you may define the $guarded property as an empty array:
Other Creation Methods
firstOrCreate/ firstOrNew
There are two other methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew. 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 from the first parameter, along with those in the optional second parameter.
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 call save manually to persist it:
updateOrCreate
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 updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model, so there's no need to call save():
Deleting Models
To delete a model, call the delete 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 delete method. However, if you know the primary key of the model, you may delete the model without retrieving it by calling the destroy method. In addition to a single primary key as its argument, the destroy method will accept multiple primary keys, an array of primary keys, or a collection of primary keys:
Deleting Models By Query
You can 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 deleting and deleted 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 deleted_at attribute is set on the model and inserted into the database. If a model has a non-null deleted_at value, the model has been soft deleted. To enable soft deletes for a model, use the IlluminateDatabaseEloquentSoftDeletes trait on the model:
Laravel 5.8
{tip} 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. 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 trashed 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 withTrashed method on the query:
The withTrashed method may also be used on a relationship query:
Retrieving Only Soft Deleted Models
The onlyTrashed 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 restore method on a model instance:
You may also use the restore 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 withTrashed method, the restore 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 forceDelete method:
Replicating Models
You may create an unsaved copy of a model instance using the replicate method. This is particularly useful when you have model instances that share many of the same attributes:
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 IlluminateDatabaseEloquentScope interface. This interface requires you to implement one method: apply. The apply method may add where 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 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 should override a given model's booted method and use the addGlobalScope method:
After adding the scope, a query to User::all() 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 withoutGlobalScope 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 withoutGlobalScopes 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 scope.
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 scope prefix when calling the method. You can even chain calls to various scopes, for example:
Combining multiple Eloquent model scopes via an or query operator may require the use of Closure callbacks:
However, since this can be cumbersome, Laravel provides a 'higher order' orWhere method that allows you to fluently chain these 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. Scope parameters should be defined after the $query parameter:
Now, you may pass the parameters when calling the scope:
Comparing Models
Sometimes you may need to determine if two models are the 'same'. The is method may be used to quickly verify two models have same primary key, table, and database connection:
Events
Eloquent models fire several events, allowing you to hook into the following points in a model's lifecycle: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. Events allow you to easily execute code each time a specific model class is saved or updated in the database. Each event receives the instance of the model through its constructor.
The retrieved event will fire 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 fire. If a model already existed in the database and the save method is called, the updating / updated events will fire. However, in both cases, the saving / saved events will fire.
{note} When issuing a mass update or delete via Eloquent, the saved, updated, deleting, and deleted model events will not be fired for the affected models. This is because the models are never actually retrieved when issuing a mass update or delete.
To get started, define a $dispatchesEvents property on your Eloquent model that maps various points of the Eloquent model's lifecycle to your own event classes:
After defining and mapping your Eloquent events, you may use event listeners to handle the events.
Using Closures
Instead of using custom event classes, you may register Closures that execute when various model events are fired. Typically, you should register these Closures in the booted method of your model:
Observers
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. 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. 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, use the observe method on the model you wish to observe. You may register observers in the boot method of one of your service providers. In this example, we'll register the observer in the AppServiceProvider:
- Running Migrations
- Tables
- Columns
- Indexes
Introduction
Migrations are like version control for your database, allowing your team to modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.
The Laravel Schemafacade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems.
Generating Migrations
To create a migration, use the make:migrationArtisan command:
Laravel 7
The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp, which allows Laravel to determine the order of the migrations.
{tip} Migration stubs may be customized using stub publishing
The --table and --create options may also be used to indicate the name of the table and whether or not the migration will be creating a new table. These options pre-fill the generated migration stub file with the specified table:
If you would like to specify a custom output path for the generated migration, you may use the --path option when executing the make:migration command. The given path should be relative to your application's base path.
Migration Structure
A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method.
Within both of these methods you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema builder, check out its documentation. For example, the following migration creates a flights table:
Running Migrations
To run all of your outstanding migrations, execute the migrate Artisan command:
{note} If you are using the Homestead virtual machine, you should run this command from within your virtual machine.
Forcing Migrations To Run In Production
Some migration operations are destructive, which means they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before the commands are executed. To force the commands to run without a prompt, use the --force flag:
Rolling Back Migrations
To roll back the latest migration operation, you may use the rollback command. This command rolls back the last 'batch' of migrations, which may include multiple migration files:
You may roll back a limited number of migrations by providing the step option to the rollback command. For example, the following command will roll back the last five migrations:
The migrate:reset command will roll back all of your application's migrations:
Roll Back & Migrate Using A Single Command
The migrate:refresh command will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database:
You may roll back & re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will roll back & re-migrate the last five migrations:
Drop All Tables & Migrate
The migrate:fresh command will drop all tables from the database and then execute the migrate command:
Tables
Creating Tables
To create a new database table, use the create method on the Schema facade. The create method accepts two arguments: the first is the name of the table, while the second is a Closure which receives a Blueprint object that may be used to define the new table:
When creating the table, you may use any of the schema builder's column methods to define the table's columns.
Checking For Table / Column Existence
You may check for the existence of a table or column using the hasTable and hasColumn methods:
Database Connection & Table Options
If you want to perform a schema operation on a database connection that is not your default connection, use the connection method:
You may use the following commands on the schema builder to define the table's options:
| Command | Description |
|---|---|
$table->engine = 'InnoDB'; | Specify the table storage engine (MySQL). |
$table->charset = 'utf8'; | Specify a default character set for the table (MySQL). |
$table->collation = 'utf8_unicode_ci'; | Specify a default collation for the table (MySQL). |
$table->temporary(); | Create a temporary table (except SQL Server). |
Renaming / Dropping Tables
To rename an existing database table, use the rename method:
To drop an existing table, you may use the drop or dropIfExists methods:
Renaming Tables With Foreign Keys
Before renaming a table, you should verify that any foreign key constraints on the table have an explicit name in your migration files instead of letting Laravel assign a convention based name. Otherwise, the foreign key constraint name will refer to the old table name.
Columns
Creating Columns
The table method on the Schema facade may be used to update existing tables. Like the create method, the table method accepts two arguments: the name of the table and a Closure that receives a Blueprint instance you may use to add columns to the table:
Available Column Types
The schema builder contains a variety of column types that you may specify when building your tables:
| Command | Description |
|---|---|
$table->id(); | Alias of $table->bigIncrements('id'). |
$table->foreignId('user_id'); | Alias of $table->unsignedBigInteger('user_id'). |
$table->bigIncrements('id'); | Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column. |
$table->bigInteger('votes'); | BIGINT equivalent column. |
$table->binary('data'); | BLOB equivalent column. |
$table->boolean('confirmed'); | BOOLEAN equivalent column. |
$table->char('name', 100); | CHAR equivalent column with a length. |
$table->date('created_at'); | DATE equivalent column. |
$table->dateTime('created_at', 0); | DATETIME equivalent column with precision (total digits). |
$table->dateTimeTz('created_at', 0); | DATETIME (with timezone) equivalent column with precision (total digits). |
$table->decimal('amount', 8, 2); | DECIMAL equivalent column with precision (total digits) and scale (decimal digits). |
$table->double('amount', 8, 2); | DOUBLE equivalent column with precision (total digits) and scale (decimal digits). |
$table->enum('level', ['easy', 'hard']); | ENUM equivalent column. |
$table->float('amount', 8, 2); | FLOAT equivalent column with a precision (total digits) and scale (decimal digits). |
$table->geometry('positions'); | GEOMETRY equivalent column. |
$table->geometryCollection('positions'); | GEOMETRYCOLLECTION equivalent column. |
$table->increments('id'); | Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column. |
$table->integer('votes'); | INTEGER equivalent column. |
$table->ipAddress('visitor'); | IP address equivalent column. |
$table->json('options'); | JSON equivalent column. |
$table->jsonb('options'); | JSONB equivalent column. |
$table->lineString('positions'); | LINESTRING equivalent column. |
$table->longText('description'); | LONGTEXT equivalent column. |
$table->macAddress('device'); | MAC address equivalent column. |
$table->mediumIncrements('id'); | Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column. |
$table->mediumInteger('votes'); | MEDIUMINT equivalent column. |
$table->mediumText('description'); | MEDIUMTEXT equivalent column. |
$table->morphs('taggable'); | Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns. |
$table->uuidMorphs('taggable'); | Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns. |
$table->multiLineString('positions'); | MULTILINESTRING equivalent column. |
$table->multiPoint('positions'); | MULTIPOINT equivalent column. |
$table->multiPolygon('positions'); | MULTIPOLYGON equivalent column. |
$table->nullableMorphs('taggable'); | Adds nullable versions of morphs() columns. |
$table->nullableUuidMorphs('taggable'); | Adds nullable versions of uuidMorphs() columns. |
$table->nullableTimestamps(0); | Alias of timestamps() method. |
$table->point('position'); | POINT equivalent column. |
$table->polygon('positions'); | POLYGON equivalent column. |
$table->rememberToken(); | Adds a nullable remember_token VARCHAR(100) equivalent column. |
$table->set('flavors', ['strawberry', 'vanilla']); | SET equivalent column. |
$table->smallIncrements('id'); | Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column. |
$table->smallInteger('votes'); | SMALLINT equivalent column. |
$table->softDeletes('deleted_at', 0); | Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes with precision (total digits). |
$table->softDeletesTz('deleted_at', 0); | Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes with precision (total digits). |
$table->string('name', 100); | VARCHAR equivalent column with a length. |
$table->text('description'); | TEXT equivalent column. |
$table->time('sunrise', 0); | TIME equivalent column with precision (total digits). |
$table->timeTz('sunrise', 0); | TIME (with timezone) equivalent column with precision (total digits). |
$table->timestamp('added_on', 0); | TIMESTAMP equivalent column with precision (total digits). |
$table->timestampTz('added_on', 0); | TIMESTAMP (with timezone) equivalent column with precision (total digits). |
$table->timestamps(0); | Adds nullable created_at and updated_at TIMESTAMP equivalent columns with precision (total digits). |
$table->timestampsTz(0); | Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns with precision (total digits). |
$table->tinyIncrements('id'); | Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column. |
$table->tinyInteger('votes'); | TINYINT equivalent column. |
$table->unsignedBigInteger('votes'); | UNSIGNED BIGINT equivalent column. |
$table->unsignedDecimal('amount', 8, 2); | UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits). |
$table->unsignedInteger('votes'); | UNSIGNED INTEGER equivalent column. |
$table->unsignedMediumInteger('votes'); | UNSIGNED MEDIUMINT equivalent column. |
$table->unsignedSmallInteger('votes'); | UNSIGNED SMALLINT equivalent column. |
$table->unsignedTinyInteger('votes'); | UNSIGNED TINYINT equivalent column. |
$table->uuid('id'); | UUID equivalent column. |
$table->year('birth_year'); | YEAR equivalent column. |
Column Modifiers
In addition to the column types listed above, there are several column 'modifiers' you may use while adding a column to a database table. For example, to make the column 'nullable', you may use the nullable method:
The following list contains all available column modifiers. This list does not include the index modifiers:
| Modifier | Description |
|---|---|
->after('column') | Place the column 'after' another column (MySQL) |
->autoIncrement() | Set INTEGER columns as auto-increment (primary key) |
->charset('utf8') | Specify a character set for the column (MySQL) |
->collation('utf8_unicode_ci') | Specify a collation for the column (MySQL/PostgreSQL/SQL Server) |
->comment('my comment') | Add a comment to a column (MySQL/PostgreSQL) |
->default($value) | Specify a 'default' value for the column |
->first() | Place the column 'first' in the table (MySQL) |
->nullable($value = true) | Allows (by default) NULL values to be inserted into the column |
->storedAs($expression) | Create a stored generated column (MySQL) |
->unsigned() | Set INTEGER columns as UNSIGNED (MySQL) |
->useCurrent() | Set TIMESTAMP columns to use CURRENT_TIMESTAMP as default value |
->virtualAs($expression) | Create a virtual generated column (MySQL) |
->generatedAs($expression) | Create an identity column with specified sequence options (PostgreSQL) |
->always() | Defines the precedence of sequence values over input for an identity column (PostgreSQL) |
Default Expressions
The default modifier accepts a value or an IlluminateDatabaseQueryExpression instance. Using an Expression instance will prevent wrapping the value in quotes and allow you to use database specific functions. One situation where this is particularly useful is when you need to assign default values to JSON columns:
{note} Support for default expressions depends on your database driver, database version, and the field type. Please refer to the appropriate documentation for compatibility. Also note that using database specific functions may tightly couple you to a specific driver.
Modifying Columns
Prerequisites
/euro-truck-simulator-2-product-key-generator-download.html. Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the required adjustments:
Updating Column Attributes
The change method allows you to modify type and attributes of existing columns. For example, you may wish to increase the size of a string column. To see the change method in action, let's increase the size of the name column from 25 to 50:
We could also modify a column to be nullable:
{note} Only the following column types can be 'changed': bigInteger, binary, boolean, date, dateTime, dateTimeTz, decimal, integer, json, longText, mediumText, smallInteger, string, text, time, unsignedBigInteger, unsignedInteger, unsignedSmallInteger and uuid.
Renaming Columns
To rename a column, you may use the renameColumn method on the schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file:
{note} Renaming any column in a table that also has a column of type enum is not currently supported.
Dropping Columns
To drop a column, use the dropColumn method on the schema builder. Before dropping columns from a SQLite database, you will need to add the doctrine/dbal dependency to your composer.json file and run the composer update command in your terminal to install the library:
You may drop multiple columns from a table by passing an array of column names to the dropColumn method:
{note} Dropping or modifying multiple columns within a single migration while using a SQLite database is not supported.
Available Command Aliases
| Command | Description |
|---|---|
$table->dropMorphs('morphable'); | Drop the morphable_id and morphable_type columns. |
$table->dropRememberToken(); | Drop the remember_token column. |
$table->dropSoftDeletes(); | Drop the deleted_at column. |
$table->dropSoftDeletesTz(); | Alias of dropSoftDeletes() method. |
$table->dropTimestamps(); | Drop the created_at and updated_at columns. |
$table->dropTimestampsTz(); | Alias of dropTimestamps() method. |
Indexes
Creating Indexes
The Laravel schema builder supports several types of indexes. The following example creates a new email column and specifies that its values should be unique. To create the index, we can chain the unique method onto the column definition:
Alternatively, you may create the index after defining the column. For example:
You may even pass an array of columns to an index method to create a compound (or composite) index:
Laravel will automatically generate an index name based on the table, column names, and the index type, but you may pass a second argument to the method to specify the index name yourself:
Available Index Types
Each index method accepts an optional second argument to specify the name of the index. If omitted, the name will be derived from the names of the table and column(s) used for the index, as well as the index type.
| Command | Description |
|---|---|
$table->primary('id'); | Adds a primary key. |
$table->primary(['id', 'parent_id']); | Adds composite keys. |
$table->unique('email'); | Adds a unique index. |
$table->index('state'); | Adds a plain index. |
$table->spatialIndex('location'); | Adds a spatial index. (except SQLite) |
Index Lengths & MySQL / MariaDB
Laravel uses the utf8mb4 character set by default, which includes support for storing 'emojis' in the database. If you are running a version of MySQL older than the 5.7.7 release or MariaDB older than the 10.2.2 release, you may need to manually configure the default string length generated by migrations in order for MySQL to create indexes for them. You may configure this by calling the Schema::defaultStringLength method within your AppServiceProvider:
Alternatively, you may enable the innodb_large_prefix option for your database. Refer to your database's documentation for instructions on how to properly enable this option.
Renaming Indexes
To rename an index, you may use the renameIndex method. This method accepts the current index name as its first argument and the desired new name as its second argument:
Dropping Indexes
To drop an index, you must specify the index's name. By default, Laravel automatically assigns an index name based on the table name, the name of the indexed column, and the index type. Here are some examples:
| Command | Description |
|---|---|
$table->dropPrimary('users_id_primary'); | Drop a primary key from the 'users' table. |
$table->dropUnique('users_email_unique'); | Drop a unique index from the 'users' table. |
$table->dropIndex('geo_state_index'); | Drop a basic index from the 'geo' table. |
$table->dropSpatialIndex('geo_location_spatialindex'); | Drop a spatial index from the 'geo' table (except SQLite). |
If you pass an array of columns into a method that drops indexes, the conventional index name will be generated based on the table name, columns and key type:
Foreign Key Constraints
Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:
Since this syntax is rather verbose, Laravel provides additional, terser methods that use convention to provide a better developer experience. The example above could be written like so:
The foreignId method is an alias for unsignedBigInteger while the constrained method will use convention to determine the table and column name being referenced.
You may also specify the desired action for the 'on delete' and 'on update' properties of the constraint:
Laravel 5.3 Generate Key Generator
To drop a foreign key, you may use the dropForeign method, passing the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes, based on the table name and the columns in the constraint, followed by a '_foreign' suffix:
Alternatively, you may pass an array containing the column name that holds the foreign key to the dropForeign method. The array will be automatically converted using the constraint name convention used by Laravel's schema builder:
Laravel Key Generate
You may enable or disable foreign key constraints within your migrations by using the following methods:
Laravel 5.3 Generate Key Code
{note} SQLite disables foreign key constraints by default. When using SQLite, make sure to enable foreign key support in your database configuration before attempting to create them in your migrations. In addition, SQLite only supports foreign keys upon creation of the table and not when tables are altered.