Php Artisan Generate App Key
- Php Artisan Generate App Key Finder
- Php Artisan Generate App Key In Word
- Php Artisan Generate App Key In Windows 10
- Introduction
- Writing Commands
- Defining Input Expectations
- Command I/O
- Programmatically Executing Commands
Introduction
Key文字列の設定 「key」には32文字のランダムな文字列を入れる。ただし「composer create-project」を使ったインストールでは自動的に挿入されているので不要である。. Apr 10, 2020 Questions: I’m trying out the PHP micro Framework Lumen (from Laravel). One of my first steps was to look into the.env.example file and make a copy of it to have my.env file. There is a variable APPKEY just like there is in Laravel. Now I tried out the simple command php artisan key:generate. Sep 17, 2018 To create a new key, you could generate one yourself and paste it into your.env, or you can run php artisan key:generate to have Laravel create and insert one automatically for you. Once your app is running, there's one place it uses the APPKEY: cookies. Laravel uses the key for all encrypted cookies, including the session cookie, before handing them off to the user's browser, and it uses it to. Php artisan list. Every command also includes a 'help' screen which displays and describes the command's available arguments and options. To view a help screen, precede the name of the command with help: php artisan help migrate. Tinker (REPL) Laravel Tinker is a powerful REPL for the Laravel framework, powered by the PsySH package. To create a new command, use the make:command Artisan command. This command will create a new command class in the app/Console/Commands directory. Don't worry if this directory does not exist in your application, since it will be created the first time you run the make:command Artisan command.
Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application. To view a list of all available Artisan commands, you may use the list
command:
Every command also includes a 'help' screen which displays and describes the command's available arguments and options. To view a help screen, precede the name of the command with help
:
Tinker (REPL)
Laravel Tinker is a powerful REPL for the Laravel framework, powered by the PsySH package.
Installation
All Laravel applications include Tinker by default. However, you may install it manually if needed using Composer:
Usage
Tinker allows you to interact with your entire Laravel application on the command line, including the Eloquent ORM, jobs, events, and more. To enter the Tinker environment, run the tinker
Artisan command:
Apr 09, 2020 SSH public and private keys imported into user accounts that are remotely authenticated through a AAA protocol (such as RADIUS or TACACS+) for the purpose of SSH Passwordless File Copy will not persist when the Nexus device is reloaded unless a local user account with the same name as the remote user account is configured on the device before the SSH keys are imported. Enter SSH keys. These cannot be brute-forced – they are simply too complex. If you can, disable password logins in your “sshdconfig” file (on the server) and use keys instead. In case you travel and can’t carry your laptop with you, just keep your private key on a. To disable SSH, you delete all of the host keys from the device. When a host key is generated, it is saved to the flash memory of all management modules. When a host key is is deleted, it is deleted from the flash memory of all management modules. The time to initially generate SSH keys varies depending on the configuration, and can be from a under a minute to several minutes. Ssh server is enabled cannot delete generate the keys.
You can publish Tinker's configuration file using the vendor:publish
command:
{note} The dispatch
helper function and dispatch
method on the Dispatchable
class depends on garbage collection to place the job on the queue. Therefore, when using tinker, you should use Bus::dispatch
or Queue::push
to dispatch jobs.
Command Whitelist
Tinker utilizes a white-list to determine which Artisan commands are allowed to be run within its shell. By default, you may run the clear-compiled
, down
, env
, inspire
, migrate
, optimize
, and up
commands. If you would like to white-list more commands you may add them to the commands
array in your tinker.php
configuration file:
Alias Blacklist
Typically, Tinker automatically aliases classes as you require them in Tinker. However, you may wish to never alias some classes. You may accomplish this by listing the classes in the dont_alias
array of your tinker.php
configuration file:
Writing Commands
In addition to the commands provided with Artisan, you may also build your own custom commands. Commands are typically stored in the app/Console/Commands
directory; however, you are free to choose your own storage location as long as your commands can be loaded by Composer.
Generating Commands
To create a new command, use the make:command
Artisan command. This command will create a new command class in the app/Console/Commands
directory. Don't worry if this directory does not exist in your application, since it will be created the first time you run the make:command
Artisan command. The generated command will include the default set of properties and methods that are present on all commands:
Command Structure
After generating your command, you should fill in the signature
and description
properties of the class, which will be used when displaying your command on the list
screen. The handle
method will be called when your command is executed. You may place your command logic in this method.
{tip} For greater code reuse, it is good practice to keep your console commands light and let them defer to application services to accomplish their tasks. In the example below, note that we inject a service class to do the 'heavy lifting' of sending the e-mails.
Let's take a look at an example command. Note that we are able to inject any dependencies we need into the command's handle
method. The Laravel service container will automatically inject all dependencies that are type-hinted in this method's signature:
Closure Commands
Closure based commands provide an alternative to defining console commands as classes. In the same way that route Closures are an alternative to controllers, think of command Closures as an alternative to command classes. Within the commands
method of your app/Console/Kernel.php
file, Laravel loads the routes/console.php
file:
Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. Within this file, you may define all of your Closure based routes using the Artisan::command
method. The command
method accepts two arguments: the command signature and a Closure which receives the commands arguments and options:
The Closure is bound to the underlying command instance, so you have full access to all of the helper methods you would typically be able to access on a full command class.
Type-Hinting Dependencies
In addition to receiving your command's arguments and options, command Closures may also type-hint additional dependencies that you would like resolved out of the service container:
Closure Command Descriptions
When defining a Closure based command, you may use the describe
method to add a description to the command. This description will be displayed when you run the php artisan list
or php artisan help
commands:
Defining Input Expectations
When writing console commands, it is common to gather input from the user through arguments or options. Laravel makes it very convenient to define the input you expect from the user using the signature
property on your commands. The signature
property allows you to define the name, arguments, and options for the command in a single, expressive, route-like syntax.
Arguments
All user supplied arguments and options are wrapped in curly braces. In the following example, the command defines one required argument: user
:
You may also make arguments optional and define default values for arguments:
Options
Options, like arguments, are another form of user input. Options are prefixed by two hyphens (--
) when they are specified on the command line. There are two types of options: those that receive a value and those that don't. Options that don't receive a value serve as a boolean 'switch'. Let's take a look at an example of this type of option:
In this example, the --queue
switch may be specified when calling the Artisan command. If the --queue
switch is passed, the value of the option will be true
. Otherwise, the value will be false
:
Options With Values
Next, let's take a look at an option that expects a value. If the user must specify a value for an option, suffix the option name with a =
sign:
In this example, the user may pass a value for the option like so:
You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used:
Option Shortcuts
To assign a shortcut when defining an option, you may specify it before the option name and use a delimiter to separate the shortcut from the full option name:
Input Arrays
If you would like to define arguments or options to expect array inputs, you may use the *
character. First, let's take a look at an example that specifies an array argument:
When calling this method, the user
arguments may be passed in order to the command line. For example, the following command will set the value of user
to ['foo', 'bar']
:
When defining an option that expects an array input, each option value passed to the command should be prefixed with the option name:
Input Descriptions
You may assign descriptions to input arguments and options by separating the parameter from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines:
Command I/O
Retrieving Input
While your command is executing, you will obviously need to access the values for the arguments and options accepted by your command. To do so, you may use the argument
and option
methods:
If you need to retrieve all of the arguments as an array
, call the arguments
method:
Options may be retrieved just as easily as arguments using the option
method. To retrieve all of the options as an array, call the options
method:
If the argument or option does not exist, null
will be returned.
Prompting For Input
In addition to displaying output, you may also ask the user to provide input during the execution of your command. The ask
method will prompt the user with the given question, accept their input, and then return the user's input back to your command:
The secret
method is similar to ask
, but the user's input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as a password:
Asking For Confirmation
If you need to ask the user for a simple confirmation, you may use the confirm
method. By default, this method will return false
. However, if the user enters y
or yes
in response to the prompt, the method will return true
.
Auto-Completion
The anticipate
method can be used to provide auto-completion for possible choices. The user can still choose any answer, regardless of the auto-completion hints:
Alternatively, you may pass a Closure as the second argument to the anticipate
method. The Closure will be called each time the user types an input character. The Closure should accept a string parameter containing the user's input so far, and return an array of options for auto-completion:
Multiple Choice Questions
If you need to give the user a predefined set of choices, you may use the choice
method. You may set the array index of the default value to be returned if no option is chosen:
In addition, the choice
method accepts optional fourth and fifth arguments for determining the maximum number of attempts to select a valid response and whether multiple selections are permitted:
Writing Output
To send output to the console, use the line
, info
, comment
, question
and error
methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let's display some general information to the user. Typically, the info
method will display in the console as green text:
To display an error message, use the error
method. Error message text is typically displayed in red:
If you would like to display plain, uncolored console output, use the line
method:
Table Layouts
The table
method makes it easy to correctly format multiple rows / columns of data. Just pass in the headers and rows to the method. The width and height will be dynamically calculated based on the given data:
Progress Bars
For long running tasks, it could be helpful to show a progress indicator. Using the output object, we can start, advance and stop the Progress Bar. First, define the total number of steps the process will iterate through. Then, advance the Progress Bar after processing each item:
For more advanced options, check out the Symfony Progress Bar component documentation.
Registering Commands
Because of the load
method call in your console kernel's commands
method, all commands within the app/Console/Commands
directory will automatically be registered with Artisan. In fact, you are free to make additional calls to the load
method to scan other directories for Artisan commands:
You may also manually register commands by adding its class name to the $commands
property of your app/Console/Kernel.php
file. When Artisan boots, all the commands listed in this property will be resolved by the service container and registered with Artisan:
Programmatically Executing Commands
Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the call
method on the Artisan
facade to accomplish this. The call
method accepts either the command's name or class as the first argument, and an array of command parameters as the second argument. The exit code will be returned:
Alternatively, you may pass the entire Artisan command to the call
method as a string:
Using the queue
method on the Artisan
facade, you may even queue Artisan commands so they are processed in the background by your queue workers. Before using this method, make sure you have configured your queue and are running a queue listener:
You may also specify the connection or queue the Artisan command should be dispatched to:
Passing Array Values
If your command defines an option that accepts an array, you may pass an array of values to that option:
Passing Boolean Values
If you need to specify the value of an option that does not accept string values, such as the --force
flag on the migrate:refresh
command, you should pass true
or false
:
Calling Commands From Other Commands
Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the call
method. This call
method accepts the command name and an array of command parameters:
If you would like to call another console command and suppress all of its output, you may use the callSilent
method. The callSilent
method has the same signature as the call
method:
Stub Customization
The Artisan console's make
commands are used to create a variety of classes, such as controllers, jobs, migrations, and tests. These classes are generated using 'stub' files that are populated with values based on your input. However, you may sometimes wish to make small changes to files generated by Artisan. To accomplish this, you may use the stub:publish
command to publish the most common stubs for customization:
The published stubs will be located within a stubs
directory in the root of your application. Any changes you make to these stubs will be reflected when you generate their corresponding classes using Artisan make
commands.
- 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 Schema
facade 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:migration
Artisan command:
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
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:
Php Artisan Generate App Key Finder
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:
Php Artisan Generate App Key In Word
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:
You may enable or disable foreign key constraints within your migrations by using the following methods:
Php Artisan Generate App Key In Windows 10
{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.