Asteps To Take After Key Generate Laravel
- Introduction
- Authentication Quickstart
- Manually Authenticating Users
- HTTP Basic Authentication
- Logging Out
- Adding Custom Guards
- Adding Custom User Providers
- Steps To Take After Key Generate Laravel
- Steps To Take After Key Generate Laravel Download
- Steps To Take After Key Generate Laravel Id
I appreciate that this may be a stupid question but what is the App Key used for and how should it be used.where and when? When I run the command artisan key:generate locally it saves it to the.env file, should I then copy the environment variable to my Forge installation? Homestead and SSH Keys Posted 4 years ago by xtremer360 I am tired of the continuous issues with Mamp Pro and I am trying to set up Vagrant and Homestead on my IMac which has Yosemite installed currently. Minor issue there, I'm trying to use php artisan key:generate, to set up my key, but it doesn't get set anywhere despite the success message that I get in the console. Not a big deal in itself as I just copy the key shown and paste it in my.env file, but just wondering why it's not working for me, never has. Any idea would be helpful. Dec 29, 2017 Create REST API in Laravel with authentication using Passport. It will create token keys for security. So let’s run below command. In this step, we will create API routes. Nov 29, 2015 This is a really really short one. I just needed to generate a random password for a user and noticed that Google doesn't really give a one-line answer, which is really simple. Nov 29, 2015 I just needed to generate a random password for a user and noticed that Google doesn't really give a one-line answer, which is really simple. How to generate random password in Laravel. November 29, 2015. Laravel Two-Step Registration: Optional Fields for.
Introduction
{tip} Want to get started fast? Install the laravel/ui
Composer package and run php artisan ui vue --auth
in a fresh Laravel application. After migrating your database, navigate your browser to http://your-app.test/register
or any other URL that is assigned to your application. These commands will take care of scaffolding your entire authentication system!
Laravel makes implementing authentication very simple. In fact, almost everything is configured for you out of the box. The authentication configuration file is located at config/auth.php
, which contains several well documented options for tweaking the behavior of the authentication services.
At its core, Laravel's authentication facilities are made up of 'guards' and 'providers'. Guards define how users are authenticated for each request. For example, Laravel ships with a session
guard which maintains state using session storage and cookies.
Providers define how users are retrieved from your persistent storage. Laravel ships with support for retrieving users using Eloquent and the database query builder. However, you are free to define additional providers as needed for your application.
Don't worry if this all sounds confusing now! Many applications will never need to modify the default authentication configuration.
Database Considerations
By default, Laravel includes an AppUser
Eloquent model in your app
directory. This model may be used with the default Eloquent authentication driver. If your application is not using Eloquent, you may use the database
authentication driver which uses the Laravel query builder.
When building the database schema for the AppUser
model, make sure the password column is at least 60 characters in length. Maintaining the default string column length of 255 characters would be a good choice.
Also, you should verify that your users
(or equivalent) table contains a nullable, string remember_token
column of 100 characters. This column will be used to store a token for users that select the 'remember me' option when logging into your application.
Authentication Quickstart
Routing
Laravel's laravel/ui
package provides a quick way to scaffold all of the routes and views you need for authentication using a few simple commands:
This command should be used on fresh applications and will install a layout view, registration and login views, as well as routes for all authentication end-points. A HomeController
will also be generated to handle post-login requests to your application's dashboard.
The laravel/ui
package also generates several pre-built authentication controllers, which are located in the AppHttpControllersAuth
namespace. The RegisterController
handles new user registration, the LoginController
handles authentication, the ForgotPasswordController
handles e-mailing links for resetting passwords, and the ResetPasswordController
contains the logic to reset passwords. Each of these controllers uses a trait to include their necessary methods. For many applications, you will not need to modify these controllers at all.
{tip} If your application doesn’t need registration, you may disable it by removing the newly created RegisterController
and modifying your route declaration: Auth::routes(['register' => false]);
.
Creating Applications Including Authentication
If you are starting a brand new application and would like to include the authentication scaffolding, you may use the --auth
directive when creating your application. This command will create a new application with all of the authentication scaffolding compiled and installed:
Views
As mentioned in the previous section, the laravel/ui
package's php artisan ui vue --auth
command will create all of the views you need for authentication and place them in the resources/views/auth
directory.
The ui
command will also create a resources/views/layouts
directory containing a base layout for your application. All of these views use the Bootstrap CSS framework, but you are free to customize them however you wish.
Authenticating
Now that you have routes and views setup for the included authentication controllers, you are ready to register and authenticate new users for your application! You may access your application in a browser since the authentication controllers already contain the logic (via their traits) to authenticate existing users and store new users in the database.
Path Customization
When a user is successfully authenticated, they will be redirected to the /home
URI. You can customize the post-authentication redirect path using the HOME
constant defined in your RouteServiceProvider
:
If you need more robust customization of the response returned when a user is authenticated, Laravel provides an empty authenticated(Request $request, $user)
method that may be overwritten if desired:
Username Customization
By default, Laravel uses the email
field for authentication. If you would like to customize this, you may define a username
method on your LoginController
:
Guard Customization
You may also customize the 'guard' that is used to authenticate and register users. To get started, define a guard
method on your LoginController
, RegisterController
, and ResetPasswordController
. The method should return a guard instance:
Validation / Storage Customization
To modify the form fields that are required when a new user registers with your application, or to customize how new users are stored into your database, you may modify the RegisterController
class. This class is responsible for validating and creating new users of your application.
The validator
method of the RegisterController
contains the validation rules for new users of the application. You are free to modify this method as you wish.
The create
method of the RegisterController
is responsible for creating new AppUser
records in your database using the Eloquent ORM. You are free to modify this method according to the needs of your database.
Retrieving The Authenticated User
You may access the authenticated user via the Auth
facade:
Alternatively, once a user is authenticated, you may access the authenticated user via an IlluminateHttpRequest
instance. Remember, type-hinted classes will automatically be injected into your controller methods:
Determining If The Current User Is Authenticated
To determine if the user is already logged into your application, you may use the check
method on the Auth
facade, which will return true
if the user is authenticated:
https://blocksyellow987.weebly.com/blog/p2-viewer-download-for-mac. {tip} Even though it is possible to determine if a user is authenticated using the check
method, you will typically use a middleware to verify that the user is authenticated before allowing the user access to certain routes / controllers. To learn more about this, check out the documentation on protecting routes.
Protecting Routes
Route middleware can be used to only allow authenticated users to access a given route. Laravel ships with an auth
middleware, which is defined at IlluminateAuthMiddlewareAuthenticate
. Since this middleware is already registered in your HTTP kernel, all you need to do is attach the middleware to a route definition:
If you are using controllers, you may call the middleware
method from the controller's constructor instead of attaching it in the route definition directly:
Redirecting Unauthenticated Users
When the auth
middleware detects an unauthorized user, it will redirect the user to the login
named route. You may modify this behavior by updating the redirectTo
function in your app/Http/Middleware/Authenticate.php
file:
Specifying A Guard
When attaching the auth
middleware to a route, you may also specify which guard should be used to authenticate the user. The guard specified should correspond to one of the keys in the guards
array of your auth.php
configuration file:
Password Confirmation
Sometimes, you may wish to require the user to confirm their password before accessing a specific area of your application. For example, you may require this before the user modifies any billing settings within the application.
To accomplish this, Laravel provides a password.confirm
middleware. Attaching the password.confirm
middleware to a route will redirect users to a screen where they need to confirm their password before they can continue:
After the user has successfully confirmed their password, the user is redirected to the route they originally tried to access. By default, after confirming their password, the user will not have to confirm their password again for three hours. You are free to customize the length of time before the user must re-confirm their password using the auth.password_timeout
configuration option.
Login Throttling
If you are using Laravel's built-in LoginController
class, the IlluminateFoundationAuthThrottlesLogins
trait will already be included in your controller. By default, the user will not be able to login for one minute if they fail to provide the correct credentials after several attempts. The throttling is unique to the user's username / e-mail address and their IP address.
Manually Authenticating Users
Note that you are not required to use the authentication controllers included with Laravel. If you choose to remove these controllers, you will need to manage user authentication using the Laravel authentication classes directly. Don't worry, it's a cinch!
We will access Laravel's authentication services via the Auth
facade, so we'll need to make sure to import the Auth
facade at the top of the class. Next, let's check out the attempt
method:
The attempt
method accepts an array of key / value pairs as its first argument. The values in the array will be used to find the user in your database table. So, in the example above, the user will be retrieved by the value of the email
column. If the user is found, the hashed password stored in the database will be compared with the password
value passed to the method via the array. You should not hash the password specified as the password
value, since the framework will automatically hash the value before comparing it to the hashed password in the database. If the two hashed passwords match an authenticated session will be started for the user.
The attempt
method will return true
if authentication was successful. Otherwise, false
will be returned.
The intended
method on the redirector will redirect the user to the URL they were attempting to access before being intercepted by the authentication middleware. A fallback URI may be given to this method in case the intended destination is not available.
Specifying Additional Conditions
If you wish, you may also add extra conditions to the authentication query in addition to the user's e-mail and password. For example, we may verify that user is marked as 'active':
{note} In these examples, email
is not a required option, it is merely used as an example. You should use whatever column name corresponds to a 'username' in your database.
Accessing Specific Guard Instances
You may specify which guard instance you would like to utilize using the guard
method on the Auth
facade. This allows you to manage authentication for separate parts of your application using entirely separate authenticatable models or user tables.
The guard name passed to the guard
method should correspond to one of the guards configured in your auth.php
configuration file:
Logging Out
To log users out of your application, you may use the logout
method on the Auth
facade. This will clear the authentication information in the user's session:
Remembering Users
If you would like to provide 'remember me' functionality in your application, you may pass a boolean value as the second argument to the attempt
method, which will keep the user authenticated indefinitely, or until they manually logout. Your users
table must include the string remember_token
column, which will be used to store the 'remember me' token.
{tip} If you are using the built-in LoginController
that is shipped with Laravel, the proper logic to 'remember' users is already implemented by the traits used by the controller.
If you are 'remembering' users, you may use the viaRemember
method to determine if the user was authenticated using the 'remember me' cookie:
Other Authentication Methods
Authenticate A User Instance
If you need to log an existing user instance into your application, you may call the login
method with the user instance. The given object must be an implementation of the IlluminateContractsAuthAuthenticatable
contract. The AppUser
model included with Laravel already implements this interface:
You may specify the guard instance you would like to use:
Authenticate A User By ID
To log a user into the application by their ID, you may use the loginUsingId
method. This method accepts the primary key of the user you wish to authenticate:
Authenticate A User Once
You may use the once
method to log a user into the application for a single request. No sessions or cookies will be utilized, which means this method may be helpful when building a stateless API:
HTTP Basic Authentication
HTTP Basic Authentication provides a quick way to authenticate users of your application without setting up a dedicated 'login' page. To get started, attach the auth.basic
middleware to your route. The auth.basic
middleware is included with the Laravel framework, so you do not need to define it:
Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the auth.basic
middleware will use the email
column on the user record as the 'username'.
A Note On FastCGI
If you are using PHP FastCGI, HTTP Basic authentication may not work correctly out of the box. The following lines should be added to your .htaccess
file:
Stateless HTTP Basic Authentication
You may also use HTTP Basic Authentication without setting a user identifier cookie in the session, which is particularly useful for API authentication. To do so, define a middleware that calls the onceBasic
method. If no response is returned by the onceBasic
method, the request may be passed further into the application:
Next, register the route middleware and attach it to a route:
Logging Out
To manually log users out of your application, you may use the logout
method on the Auth
facade. This will clear the authentication information in the user's session:
Invalidating Sessions On Other Devices
Laravel also provides a mechanism for invalidating and 'logging out' a user's sessions that are active on other devices without invalidating the session on their current device. This feature is typically utilized when a user is changing or updating their password and you would like to invalidate sessions on other devices while keeping the current device authenticated.
Before getting started, you should make sure that the IlluminateSessionMiddlewareAuthenticateSession
middleware is present and un-commented in your app/Http/Kernel.php
class' web
middleware group:
Then, you may use the logoutOtherDevices
method on the Auth
facade. This method requires the user to provide their current password, which your application should accept through an input form:
When the logoutOtherDevices
method is invoked, the user's other sessions will be invalidated entirely, meaning they will be 'logged out' of all guards they were previously authenticated by.
{note} When using the AuthenticateSession
middleware in combination with a custom route name for the login
route, you must override the unauthenticated
method on your application's exception handler to properly redirect users to your login page.
Adding Custom Guards
You may define your own authentication guards using the extend
method on the Auth
facade. You should place this call to extend
within a service provider. Since Laravel already ships with an AuthServiceProvider
, we can place the code in that provider:
As you can see in the example above, the callback passed to the extend
method should return an implementation of IlluminateContractsAuthGuard
. This interface contains a few methods you will need to implement to define a custom guard. Once your custom guard has been defined, you may use this guard in the guards
configuration of your auth.php
configuration file:
Closure Request Guards
The simplest way to implement a custom, HTTP request based authentication system is by using the Auth::viaRequest
method. This method allows you to quickly define your authentication process using a single Closure.
To get started, call the Auth::viaRequest
method within the boot
method of your AuthServiceProvider
. The viaRequest
method accepts an authentication driver name as its first argument. This name can be any string that describes your custom guard. The second argument passed to the method should be a Closure that receives the incoming HTTP request and returns a user instance or, if authentication fails, null
:
Once your custom authentication driver has been defined, you use it as a driver within guards
configuration of your auth.php
configuration file:
Adding Custom User Providers
If you are not using a traditional relational database to store your users, you will need to extend Laravel with your own authentication user provider. We will use the provider
method on the Auth
facade to define a custom user provider:
After you have registered the provider using the provider
method, you may switch to the new user provider in your auth.php
configuration file. First, define a provider
that uses your new driver:
Finally, you may use this provider in your guards
configuration:
The User Provider Contract
The IlluminateContractsAuthUserProvider
implementations are only responsible for fetching a IlluminateContractsAuthAuthenticatable
implementation out of a persistent storage system, such as MySQL, Riak, etc. These two interfaces allow the Laravel authentication mechanisms to continue functioning regardless of how the user data is stored or what type of class is used to represent it.
Let's take a look at the IlluminateContractsAuthUserProvider
contract:
The retrieveById
function typically receives a key representing the user, such as an auto-incrementing ID from a MySQL database. The Authenticatable
implementation matching the ID should be retrieved and returned by the method.
The retrieveByToken
function retrieves a user by their unique $identifier
and 'remember me' $token
, stored in a field remember_token
. As with the previous method, the Authenticatable
implementation should be returned.
The updateRememberToken
method updates the $user
field remember_token
with the new $token
. A fresh token is assigned on a successful 'remember me' login attempt or when the user is logging out.
The retrieveByCredentials
method receives the array of credentials passed to the Auth::attempt
method when attempting to sign into an application. The method should then 'query' the underlying persistent storage for the user matching those credentials. Typically, this method will run a query with a 'where' condition on $credentials['username']
. The method should then return an implementation of Authenticatable
. This method should not attempt to do any password validation or authentication.
The validateCredentials
method should compare the given $user
with the $credentials
to authenticate the user. For example, this method should probably use Hash::check
to compare the value of $user->getAuthPassword()
to the value of $credentials['password']
. This method should return true
or false
indicating on whether the password is valid.
The Authenticatable Contract
Now that we have explored each of the methods on the UserProvider
, let's take a look at the Authenticatable
contract. Remember, the provider should return implementations of this interface from the retrieveById
, retrieveByToken
, and retrieveByCredentials
methods:
This interface is simple. The getAuthIdentifierName
method should return the name of the 'primary key' field of the user and the getAuthIdentifier
method should return the 'primary key' of the user. In a MySQL back-end, again, this would be the auto-incrementing primary key. The getAuthPassword
should return the user's hashed password. This interface allows the authentication system to work with any User class, regardless of what ORM or storage abstraction layer you are using. By default, Laravel includes a User
class in the app
directory which implements this interface, so you may consult this class for an implementation example.
Events
Laravel raises a variety of events during the authentication process. You may attach listeners to these events in your EventServiceProvider
:
- 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.
Steps To Take After Key Generate Laravel
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:
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
Steps To Take After Key Generate Laravel Download
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:
Steps To Take After Key Generate Laravel Id
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:
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
Openvpn generate tls crypt key. 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:
{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.