# data[].attributes.body
https://hcode.com.br/blog/instalando-e-configurando-o-laravel-no-windows-linux-e-mac

# data[].attributes.attachment_link.readable_text
Neste artigo iremos aprender o que é o Laravel e como podemos realizar sua instalação e configuração em vários Sistemas Operacionais.

O que é Laravel?

Laravel é um dos frameworks PHP mais conhecidos e usados hoje em dia. Famoso por ter uma estrutura de pastas muito organizada e uma sintaxe elegante, seu uso e popularidade têm crescido muito nos últimos anos.

Seu projeto é Open Source e nos dá muitas vantagens. Seu ecossistema está repleto de ferramentas que facilitam o desenvolvimento de nossas aplicações. Alguns exemplos são o sistema de rotas, sistema de templates e recursos incríveis para os Bancos de Dados, como as Migrations, que são como um "controle de versão para Databases". Com o Laravel é possível criar, excluir e adicionar dados em tabelas usando apenas código, sem precisar ir para o Banco.

Por meio dessas facilidades, muitos programadores perceberam que códigos ou processos repetitivos, rotineiros, que eles levavam muito tempo para desenvolver, podem ser executados com o Laravel em alguns instantes. Ele é realmente muito prático. Com o Laravel podemos criar uma inteira aplicação em PHP, ou então uma API que será consumida por outra tecnologia, como o Angular, React ou Vue.

A comunidade do Laravel é muito ativa e sua documentação é bem completa, o que mostra que essa ferramenta tem um excelente suporte para quem deseja aprendê-la.

Instalando o Laravel

Para instalar o Laravel, é necessário ter o Composer já instalado. Se você não possuir o Composer em seu computador, poderá ver como realizar sua instalação neste vídeo que está em nosso canal no YouTube: Composer - Aprenda a instalar e configurar este gerenciador de dependências.

Também, é necessário possuir o PHP configurado em seu computador, com a versão 7.2 no mínimo.

Diferente da maioria das ferramentas, que possuem uma instalação distinta para cada Sistema Operacional, o Laravel pode ser instalado no Windows, Linux ou Mac com o mesmo comando. Incrível, não acha?

Iremos trabalhar com o Terminal neste artigo. Pode ser o Prompt de Comando no caso do Windows, ou o Terminal padrão no Linux e no Mac.

Após abri-lo, e lembrando da importância de ter o Composer instalado em nossos computadores, iremos executar o seguinte comando:

composer global require laravel/installer

Ele irá usar a nossa Internet para baixar e instalar o Laravel. Após isso o Laravel já estará disponível para o usarmos.

Também é muito simples criar um projeto em Laravel. Vamos fazer isso agora.

Para criar um projeto, iremos usar novamente a linha de comando. Podemos abrir o Terminal onde desejarmos. No meu caso, irei abri-lo na Área de Trabalho. Executaremos o comando laravel new e então informaremos o nome do projeto que estamos criando. O comando ficará dessa forma:

laravel new hcode-project

O processo de criação será iniciado, e após alguns instantes, veremos a mensagem que está na imagem abaixo:

O Laravel terá criado para nós uma pasta chamada hcode-project, que é o nome de nossa aplicação. Precisamos agora entrar neste diretório por meio do Terminal. Para isso, execute o seguinte comando:

cd hcode-project

Se abrir esse diretório no seu Editor de Texto, será possível ver toda a estrutura de pastas do Laravel. Para iniciar nossa aplicação, basta executar o comando abaixo:

php artisan serve

Veremos em nosso Terminal a seguinte resposta:

Ela informa que nosso servidor foi iniciado com sucesso e está disponível na porta 8000 do localhost. Ao acessar o endereço http://localhost:8000 no navegador, veremos o seguinte:

Nossa aplicação já está iniciada e pronta para receber mais recursos :)

Como falamos no início, uma das principais vantagens em usar o Laravel é que ele é um framework com código elegante ou eloquente, e pode ser usado para criar aplicações robustas e poderosas em menos tempo. Com certeza ele deverá crescer ainda mais nos próximos anos.

Lembrando que nós ensinamos os conceitos deste framework elegante em nosso curso Criando REST API com Laravel 5.7, onde criamos uma API usando os recursos do Laravel.

Até o próximo artigo :)

# data[].attributes.attachment_link.title
Instalando e Configurando o Laravel no Windows, Linux e Mac - Hcode

# data[].attributes.attachment_link.description
Neste artigo iremos aprender o que é o Laravel e como podemos realizar sua instalação e configuração em vários Sistemas Operacionais. Laravel é um dos frameworks PHP mais conhecidos e usados hoje em dia. Famoso por ter uma estrutura de pastas muito organizada e uma sintaxe elegante, seu uso e popularidade têm crescido muito nos últimos anos.

# data[].attributes.body
Iarlei Francisco da Cruz de Souza
Nilson Cruz Leite Neto

# data[].attributes.body
Database Migrations

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:

php artisan migrate --force

# data[].attributes.attachment_link.readable_text
Introduction

Migrations are like version control for your database, allowing your team to define and share the application's database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, 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. Typically, migrations will use this facade to create and modify database tables and columns.

Generating Migrations

You may use the make:migration Artisan command to generate a database migration. The new migration will be placed in your database/migrations directory. Each migration filename contains a timestamp that allows Laravel to determine the order of the migrations:

Laravel will use the name of the migration to attempt to guess the name of the table and whether or not the migration will be creating a new table. If Laravel is able to determine the table name from the migration name, Laravel will pre-fill the generated migration file with the specified table. Otherwise, you may simply specify the table in the migration file manually.

If you would like to specify a custom 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.

Note
Migration stubs may be customized using stub publishing.

Squashing Migrations

As you build your application, you may accumulate more and more migrations over time. This can lead to your database/migrations directory becoming bloated with potentially hundreds of migrations. If you would like, you may "squash" your migrations into a single SQL file. To get started, execute the schema:dump command:

# Dump the current database schema and prune all existing migrations...

When you execute this command, Laravel will write a "schema" file to your application's database/schema directory. The schema file's name will correspond to the database connection. Now, when you attempt to migrate your database and no other migrations have been executed, Laravel will first execute the SQL statements in the schema file of the database connection you are using. After executing the schema file's SQL statements, Laravel will execute any remaining migrations that were not part of the schema dump.

If your application's tests use a different database connection than the one you typically use during local development, you should ensure you have dumped a schema file using that database connection so that your tests are able to build your database. You may wish to do this after dumping the database connection you typically use during local development:

You should commit your database schema file to source control so that other new developers on your team may quickly create your application's initial database structure.

Warning
Migration squashing is only available for the MySQL, PostgreSQL, and SQLite databases and utilizes the database's command-line client. Schema dumps may not be restored to in-memory SQLite databases.

Migration Structure

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:

Setting The Migration Connection

If your migration will be interacting with a database connection other than your application's default database connection, you should set the $connection property of your migration:

 * The database connection that should be used by the migration.

Running Migrations

To run all of your outstanding migrations, execute the migrate Artisan command:

If you would like to see which migrations have run thus far, you may use the migrate:status Artisan command:

If you would like to see the SQL statements that will be executed by the migrations without actually running them, you may provide the --pretend flag to the migrate command:

Isolating Migration Execution

If you are deploying your application across multiple servers and running migrations as part of your deployment process, you likely do not want two servers attempting to migrate the database at the same time. To avoid this, you may use the isolated option when invoking the migrate command.

When the isolated option is provided, Laravel will acquire an atomic lock using your application's cache driver before attempting to run your migrations. All other attempts to run the migrate command while that lock is held will not execute; however, the command will still exit with a successful exit status code:

Warning To utilize this feature, your application must be using the memcached, redis, dynamodb, database, file, or array cache driver as your application's default cache driver. In addition, all servers must be communicating with the same central cache server.

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 Artisan 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 and re-migrate a limited number of migrations by providing the step option to the refresh command. For example, the following command will roll back and 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:

Warning
The migrate:fresh command will drop all database tables regardless of their prefix. This command should be used with caution when developing on a database that is shared with other applications.

Tables

Creating Tables

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 application's default connection, use the connection method:

In addition, a few other properties and methods may be used to define other aspects of the table's creation. The engine property may be used to specify the table's storage engine when using MySQL:

The charset and collation properties may be used to specify the character set and collation for the created table when using MySQL:

The temporary method may be used to indicate that the table should be "temporary". Temporary tables are only visible to the current connection's database session and are dropped automatically when the connection is closed:

If you would like to add a "comment" to a database table, you may invoke the comment method on the table instance. Table comments are currently only supported by MySQL and Postgres:

Updating Tables

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

Available Column Types

The schema builder blueprint offers a variety of methods that correspond to the different types of columns you can add to your database tables. Each of the available methods are listed in the table below:

bigIncrements()

The bigIncrements method creates an auto-incrementing UNSIGNED BIGINT (primary key) equivalent column:

bigInteger()

The bigInteger method creates a BIGINT equivalent column:

The binary method creates a BLOB equivalent column:

The boolean method creates a BOOLEAN equivalent column:

The char method creates a CHAR equivalent column with of a given length:

dateTimeTz()

The dateTimeTz method creates a DATETIME (with timezone) equivalent column with an optional precision (total digits):

The dateTime method creates a DATETIME equivalent column with an optional precision (total digits):

The date method creates a DATE equivalent column:

The decimal method creates a DECIMAL equivalent column with the given precision (total digits) and scale (decimal digits):

The double method creates a DOUBLE equivalent column with the given precision (total digits) and scale (decimal digits):

The enum method creates a ENUM equivalent column with the given valid values:

The float method creates a FLOAT equivalent column with the given precision (total digits) and scale (decimal digits):

The foreignId method creates an UNSIGNED BIGINT equivalent column:

foreignIdFor()

The foreignIdFor method adds a {column}_id UNSIGNED BIGINT equivalent column for a given model class:

foreignUlid()

The foreignUlid method creates a ULID equivalent column:

foreignUuid()

The foreignUuid method creates a UUID equivalent column:

geometryCollection()

The geometryCollection method creates a GEOMETRYCOLLECTION equivalent column:

The geometry method creates a GEOMETRY equivalent column:

The id method is an alias of the bigIncrements method. By default, the method will create an id column; however, you may pass a column name if you would like to assign a different name to the column:

increments()

The increments method creates an auto-incrementing UNSIGNED INTEGER equivalent column as a primary key:

The integer method creates an INTEGER equivalent column:

The ipAddress method creates a VARCHAR equivalent column:

When using Postgres, an INET column will be created.

The json method creates a JSON equivalent column:

The jsonb method creates a JSONB equivalent column:

lineString()

The lineString method creates a LINESTRING equivalent column:

The longText method creates a LONGTEXT equivalent column:

macAddress()

The macAddress method creates a column that is intended to hold a MAC address. Some database systems, such as PostgreSQL, have a dedicated column type for this type of data. Other database systems will use a string equivalent column:

mediumIncrements()

The mediumIncrements method creates an auto-incrementing UNSIGNED MEDIUMINT equivalent column as a primary key:

mediumInteger()

The mediumInteger method creates a MEDIUMINT equivalent column:

mediumText()

The mediumText method creates a MEDIUMTEXT equivalent column:

This method is intended to be used when defining the columns necessary for a polymorphic Eloquent relationship. In the following example, taggable_id and taggable_type columns would be created:

multiLineString()

The multiLineString method creates a MULTILINESTRING equivalent column:

multiPoint()

The multiPoint method creates a MULTIPOINT equivalent column:

multiPolygon()

The multiPolygon method creates a MULTIPOLYGON equivalent column:

nullableTimestamps()

The nullableTimestamps method is an alias of the timestamps method:

nullableMorphs()

The method is similar to the morphs method; however, the columns that are created will be "nullable":

nullableUlidMorphs()

The method is similar to the ulidMorphs method; however, the columns that are created will be "nullable":

nullableUuidMorphs()

The method is similar to the uuidMorphs method; however, the columns that are created will be "nullable":

The point method creates a POINT equivalent column:

The polygon method creates a POLYGON equivalent column:

rememberToken()

The rememberToken method creates a nullable, VARCHAR(100) equivalent column that is intended to store the current "remember me" authentication token:

The set method creates a SET equivalent column with the given list of valid values:

smallIncrements()

The smallIncrements method creates an auto-incrementing UNSIGNED SMALLINT equivalent column as a primary key:

smallInteger()

The smallInteger method creates a SMALLINT equivalent column:

softDeletesTz()

softDeletes()

The string method creates a VARCHAR equivalent column of the given length:

The text method creates a TEXT equivalent column:

The timeTz method creates a TIME (with timezone) equivalent column with an optional precision (total digits):

The time method creates a TIME equivalent column with an optional precision (total digits):

timestampTz()

The timestampTz method creates a TIMESTAMP (with timezone) equivalent column with an optional precision (total digits):

The timestamp method creates a TIMESTAMP equivalent column with an optional precision (total digits):

timestampsTz()

timestamps()

tinyIncrements()

The tinyIncrements method creates an auto-incrementing UNSIGNED TINYINT equivalent column as a primary key:

tinyInteger()

The tinyInteger method creates a TINYINT equivalent column:

The tinyText method creates a TINYTEXT equivalent column:

unsignedBigInteger()

The unsignedBigInteger method creates an UNSIGNED BIGINT equivalent column:

unsignedDecimal()

The unsignedDecimal method creates an UNSIGNED DECIMAL equivalent column with an optional precision (total digits) and scale (decimal digits):

unsignedInteger()

The unsignedInteger method creates an UNSIGNED INTEGER equivalent column:

unsignedMediumInteger()

The unsignedMediumInteger method creates an UNSIGNED MEDIUMINT equivalent column:

unsignedSmallInteger()

The unsignedSmallInteger method creates an UNSIGNED SMALLINT equivalent column:

unsignedTinyInteger()

The unsignedTinyInteger method creates an UNSIGNED TINYINT equivalent column:

ulidMorphs()

This method is intended to be used when defining the columns necessary for a polymorphic Eloquent relationship that use ULID identifiers. In the following example, taggable_id and taggable_type columns would be created:

uuidMorphs()

This method is intended to be used when defining the columns necessary for a polymorphic Eloquent relationship that use UUID identifiers. In the following example, taggable_id and taggable_type columns would be created:

The ulid method creates a ULID equivalent column:

The uuid method creates a UUID equivalent column:

The year method creates a YEAR equivalent column:

Column Modifiers

In addition to the column types listed above, there are several column "modifiers" you may use when adding a column to a database table. For example, to make the column "nullable", you may use the nullable method:

The following table contains all of the available column modifiers. This list does not include index modifiers:

Make the column "invisible" to SELECT * queries (MySQL).

->isGeometry()
Set spatial column type to geometry - the default type is geography (PostgreSQL).

Default Expressions

The default modifier accepts a value or an Illuminate\Database\Query\Expression instance. Using an Expression instance will prevent Laravel from 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:

Warning
Support for default expressions depends on your database driver, database version, and the field type. Please refer to your database's documentation.

Column Order

When using the MySQL database, the after method may be used to add columns after an existing column in the schema:

Modifying Columns

When modifying a column, you must explicitly include all of the modifiers you want to keep on the column definition - any missing attribute will be dropped. For example, to retain the unsigned, default, and comment attributes, you must call each modifier explicitly when changing the column:

Modifying Columns On SQLite

If your application is utilizing an SQLite database, you must install the doctrine/dbal package using the Composer package manager before modifying a column. The Doctrine DBAL library is used to determine the current state of the column and to create the SQL queries needed to make the requested changes to your column:

If you plan to modify columns created using the timestamp method, you must also add the following configuration to your application's config/database.php configuration file:

Renaming Columns

To rename a column, you may use the renameColumn method provided by the schema builder:

Renaming Columns On Legacy Databases

If you are running a database installation older than one of the following releases, you should ensure that you have installed the doctrine/dbal library via the Composer package manager before renaming a column:

Dropping Columns

To drop a column, you may use the dropColumn method on the schema builder:

You may drop multiple columns from a table by passing an array of column names to the dropColumn method:

Dropping Columns On Legacy Databases

If you are running a version of SQLite prior to 3.35.0, you must install the doctrine/dbal package via the Composer package manager before the dropColumn method may be used. Dropping or modifying multiple columns within a single migration while using this package is not supported.

Available Command Aliases

Laravel provides several convenient methods related to dropping common types of columns. Each of these methods is described in the table below:

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. To do so, you should call the unique method on the schema builder blueprint. This method accepts the name of the column that should receive a unique index:

You may even pass an array of columns to an index method to create a compound (or composite) index:

When creating an 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

Laravel's schema builder blueprint class provides methods for creating each type of index supported by Laravel. 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. Each of the available index methods is described in the table below:

Index Lengths & MySQL / MariaDB

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 provided by the schema builder blueprint. This method accepts the current index name as its first argument and the desired name as its second argument:

Warning
If your application is utilizing an SQLite database, you must install the doctrine/dbal package via the Composer package manager before the renameIndex method may be used.

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:

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 index type:

Foreign Key Constraints

Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. When using the foreignId method to create your column, the example above can be rewritten like so:

You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

An alternative, expressive syntax is also provided for these actions:

Any additional column modifiers must be called before the constrained method:

Dropping Foreign Keys

To drop a foreign key, you may use the dropForeign method, passing the name of the foreign key constraint to be deleted as an argument. Foreign key constraints use the same naming convention as indexes. In other words, the foreign key constraint name is based on the name of the table 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 converted to a foreign key constraint name using Laravel's constraint naming conventions:

Toggling Foreign Key Constraints

You may enable or disable foreign key constraints within your migrations by using the following methods:

Warning
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.

Events

For convenience, each migration operation will dispatch an event. All of the following events extend the base Illuminate\Database\Events\MigrationEvent class:

# data[].attributes.attachment_link.title
Laravel - The PHP Framework For Web Artisans

# data[].attributes.attachment_link.description
Migrations are like version control for your database, allowing your team to define and share the application's database schema definition. If you have ever had to tell a teammate to manually add a column to their local database schema after pulling in your changes from source control, you've faced the problem that database migrations solve.