- Eloquent: Mutators
- Database: Getting Started
- Schema Builder
- Database: Getting Started
- The PHP Framework for Web Artisans
Eloquent: MutatorsLaravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems. There is no need to clean strings being passed as bindings. You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method:. You may access each column's value by accessing the column as a property of the object:. If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single stdClass object:. If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:. If you would like to retrieve a Collection containing the values of a single column, you may use the pluck method. In this example, we'll retrieve a Collection of role titles:. If you need to work with thousands of database records, consider using the chunk method. This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure for processing. This method is very useful for writing Artisan commands that process thousands of records. For example, let's work with the entire users table in chunks of records at a time:. You may stop further chunks from being processed by returning false from the Closure :. The query builder also provides a variety of aggregate methods such as countmaxminavgand sum. You may call any of these methods after constructing your query:. Instead of using the count method to determine if any records exist that match your query's constraints, you may use the exists and doesntExist methods:. Of course, you may not always want to select all columns from a database table. Using the select method, you can specify a custom select clause for the query:. If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:. Sometimes you may need to use a raw expression in a query. To create a raw expression, you may use the DB::raw method:. Instead of using DB::rawyou may also use the following methods to insert a raw expression into various parts of your query. The selectRaw method can be used in place of select DB::raw This method accepts an optional array of bindings as its second argument:. The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query. These methods accept an optional array of bindings as their second argument:. The havingRaw and orHavingRaw methods may be used to set a raw string as the value of the having clause. The orderByRaw method may be used to set a raw string as the value of the order by clause:. The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. Of course, as you can see, you can join to multiple tables in a single query:. If you would like to perform a "left join" instead of an "inner join", use the leftJoin method. The leftJoin method has the same signature as the join method:. To perform a "cross join" use the crossJoin method with the name of the table you wish to cross join to.
Database: Getting Started
The Laravel Schema class provides a database agnostic way of manipulating tables. It works well with all of the databases supported by Laravel, and has a unified API across all of these systems. The first argument passed to the create method is the name of the table, and the second is a Closure which will receive a Blueprint object which may be used to define the new table. To specify which connection the schema operation should take place on, use the Schema::connection method:. If you are using the MySQL database, you may use the after method to specify the order of columns:. To rename a column, you may use the renameColumn method on the Schema builder. To drop a column, you may use the dropColumn method on the Schema builder. You may easily check for the existence of a table or column using the hasTable and hasColumn methods:. The schema builder supports several types of indexes. There are two ways to add them. First, you may fluently define them on a column definition, or you may add them separately:. Or, you may choose to add the indexes on separate lines. Below is a list of all available index types:. Make sure to create the foreign key column first! You may also specify options for the "on delete" and "on update" actions of the constraint:. To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:. Note: When creating a foreign key that references an incrementing integer, remember to always make the foreign key column unsigned. To drop an index you must specify the index's name. Laravel assigns a reasonable name to the indexes by default. Simply concatenate the table name, the names of the column in the index, and the index type. Here are some examples:. To drop the timestampsnullableTimestamps or softDeletes column types, you may use the following methods:. To set the storage engine for a table, set the engine property on the schema builder:. Dropping Columns To drop a column, you may use the dropColumn method on the Schema builder. Dropping Indexes To drop an index you must specify the index's name.
Laravel includes a simple method of seeding your database with test data using seed classes. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeederetc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order. To generate a seeder, execute the make:seeder Artisan command. A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories. As an example, let's modify the default DatabaseSeeder class and add a database insert statement to the run method:. They will automatically be resolved via the Laravel service container. Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories to conveniently generate large amounts of database records. First, review the model factory documentation to learn how to define your factories. Once you have defined your factories, you may use the factory helper function to insert records into your database. Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes overwhelmingly large. Pass the name of the seeder class you wish to run:. Once you have written your seeder, you may need to regenerate Composer's autoloader using the dump-autoload command:. Now you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually:. You may also seed your database using the migrate:refresh command, which will also rollback and re-run all of your migrations. This command is useful for completely re-building your database:. Some seeding operations may cause you to alter or lose data. In order to protect you from running seeding commands against your production database, you will be prompted for confirmation before the seeders are executed. To force the seeders to run without a prompt, use the --force flag:. Writing Seeders To generate a seeder, execute the make:seeder Artisan command. Using Model Factories Of course, manually specifying the attributes for each model seed is cumbersome. This command is useful for completely re-building your database: php artisan migrate:refresh --seed Forcing Seeders To Run In Production Some seeding operations may cause you to alter or lose data. To force the seeders to run without a prompt, use the --force flag: php artisan db:seed --force.
Database: Getting Started
Migrations are like version control for your database, allowing your team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily 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. To create a migration, use the make:migration Artisan command :. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations. The --table and --create options may also be used to indicate the name of the table and whether 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. 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, this migration example creates a flights table:. 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:. To rollback 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 rollback a limited number of migrations by providing the step option to the rollback command. For example, the following command will rollback the last five migrations:. 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:. The migrate:fresh command will drop all tables from the database and then execute the migrate command:. 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. You may easily check for the existence of a table or column using the hasTable and hasColumn methods:. If you want to perform a schema operation on a database connection that is not your default connection, use the connection method:. To drop an existing table, you may use the drop or dropIfExists methods:. 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. The table method on the Schema facade may be used to update existing tables.