Laravel 5.5 Key Generate

  • Running Migrations
  • Tables
  • Columns
  • Indexes

Introduction

  1. I try to Setup Laravel 5.2 on CentOS 7. When I try to generate the Application Key using the console command php artisan key:generate the format of the Application Key is not as expected (longer than 32 characters including the base64 encode string and thus not working in the Configuration file.The cypher in config/app.php is AES-256-CBC.
  2. Nov 19, 2017  For the Love of Physics - Walter Lewin - May 16, 2011 - Duration: 1:01:26. Lectures by Walter Lewin. They will make you ♥ Physics. Recommended for you.

Jan 06, 2018  php artisan key:generate. This command should generate a key file in your.env file located at the project root. If you don’t yet have a.env file at your project root then you should create one by copying the contents of file.env.example. Once you have created the.env file, run the command again and make sure that there is a key generated at property APPKEY in the file. Laravel 5.5 Lumen 5.5 RESTful API with OAuth2. This is a RESTful API with OAuth2 authentication/security developed using Laravel Lumen 5.5.0. You can use this if you want to quick start developing your own custom RESTful API by skipping 95% of your scratch works. Application Key. The next thing you should do after installing Laravel is set your application key to a random string. If you installed Laravel via Composer or the Laravel installer, this key has already been set for you by the php artisan key:generate command. Typically, this string should be 32 characters long. Sep 28, 2017  laravel uuid generator, laravel uuid primary key, laravel validate uuid, generate uuid in laravel 5.5, create uuid in laravel 5 example, laravel 5 uuid, laravel 5 webpatser/laravel-uuid example. In this post i will show you how to generate uuid in laravel 5 application. Laravel 5.5 has introduced a new command to create a model factory. Model factories come in handy when we want to generate fake data or a new instance of an object when writing tests.

Migrations are like version control for your database, allowing your team to modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to build your application's database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you've faced the problem that database migrations solve.

The Laravel Schemafacade provides database agnostic support for creating and manipulating tables across all of Laravel's supported database systems.

Generating Migrations

To create a migration, use the make:migrationArtisan command:

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.

Laravel 5 Tutorial Pdf

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:

CommandDescription
$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:

CommandDescription
$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:

ModifierDescription
->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:

Download Laravel 5

{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

CommandDescription
$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:

Laravel 5.8

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.

CommandDescription
$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:

CommandDescription
$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 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.

Laravel 5.5 will require PHP 7.0+. For the features this modern PHP version brings, please see our recap.

Laravel 5.5 will also be the next LTS (Long Term Support) release. This means bugfixes for two years and three years of security updates. That was also the case with Laravel 5.1, but its two-year window of bug fixes is coming to an end this year. Without further ado, let’s see what this new version has to offer.

Creating a New Laravel 5.5 Project

Table of Contents

Since the release has not yet officially happened, we can install the dev release version by running the command:

If you prefer not to use the Laravel installer, you can also take the Composer approach:

Once we visit the homepage of the newly set up app, we should be greeted with a welcome page similar to what we used to have in previous Laravel versions.

Rendering Mailables to the Browser

I feel this is something that will come in very handy. In the previous Laravel versions, we had to send actual emails or use an email client like Mailtrap to test email layouts, and this wasn’t a fun task. This won’t be the case any more, as with Laravel 5.5 it’s possible to render the email layout to the browser directly.

A quick walkthrough on how to achieve this: let’s create a new mailable as well as the email template for our current project:

I prefer the markdown approach since we will get a template with some content already. Let’s open our web.php file and create a test route to checkout the email layout:

routes/web.php

By visiting the route /email we should be able to preview the email template:

What’s actually going on under the hood is that with Laravel 5.5, the Mailable class implements the Renderable contract which has a render() method. This is the implementation of the render() method inside lluminate/Mail/Mailable.php:

lluminate/Mail/Mailable.php

This is the method that makes it possible to get a view. Had we tried returning an instance of a class that does not implement the Renderable contract within our routes, we’d get an UnexpectedValueException thrown.

Custom Email Themes

When using Markdown for emails, Laravel will provide a default theme. However, some people may prefer having some custom styling in their email templates for branding purposes.

To use a custom theme for a particular mailable, we first create a custom .css file containing the styles we want:

We then then specify this filename as a property in the Mailable class:

app/Mail/Welcome.php

This way, the email layout will be based on the styles we defined in the custom.css file. The good thing with this approach is that we can have different themes for different mailables.

Exception Helper Functions

Laravel 5.5 comes with two exception helper functions which will help us write more expressive code. The two helpers are the throw_if and throw_unless methods. Both take three arguments with the third argument being optional.

Let’s look at the different implementations of these exceptions:

With the throw_if helper, an exception will be thrown if the first argument evaluates to true.

Implementing the throw_unless helper is no different from what we did above, the only difference being that an exception will only be thrown if the first argument evaluates to false:

Not the best example, but serves our demonstration purposes.

Introducing the migrate:fresh Command

You’ve probably found yourself in a situation that required you to rebuild the database. With previous Laravel versions, we achieved this by running the php artisan migrate:refresh command. The migrate:refresh command rolls back all migrations based on what is specified in the down method for each migration file then runs the migrations again:

But you’ve probably run into issues with this command a couple of times, especially when working with foreign key constraints or say you have a down() method in one of your migrations that has not been well defined. When that happens, we resort to dropping the table raising issues manually most of the time – (could be from the CLI or some GUI). That’s where migrate:fresh comes to our rescue. This command drops all the tables, then runs the existing migrations again:

JSON Error Stack Traces

Not a really big change but then in previous Laravel versions, we’d see HTML markup from an API client such as Postman every time we got an error while building out APIs. In Laravel 5.5, we get a JSON stack trace rather than HTML markup if an error occurs which looks neater and easier to follow:

Automatic Package Discovery

These are the steps we follow in order to use a third party package in our Laravel projects.

  • Install the package
  • Register the package’s service provider
  • Register facades if any

As you can see, it could be simpler. Now it is.

With automatic package discovery, we’ll just require a package and start using it on the fly. Note, however, this only happens if the package provider has configured the package for autodiscovery.

Looking at the Laravel Debugbar package which has already been updated for package autodiscovery, we see that there is an extra section inside the composer.json file:

Package providers will have to update the composer.json file with an extra section, then specify the providers and any aliases for the package.

Another good thing with automatic package discovery is that things won’t break after removing a dependency. Normally, even after uninstalling a package we still have the package’s service providers and facades hanging around in the config/app.php file and this may raise issues in some cases.

With package autodiscovery, when a package is removed via Composer, then everything related to the package is also removed.

Changes to the vendor:publish Command

In previous Laravel versions, running the vendor:publish command would publish all resources from packages and some from the framework itself. Some of the resources published include migrations, views, and configs.

With Laravel 5.5, we have to be a bit more explicit on what we want to be published when running this command. If we run php artisan vendor:publish without passing any flags, we’ll be prompted to pick a provider or tag making it easier to only publish what we want. See screenshot below:

We can bypass the prompt by specifying the --all or --provider flag when running the publish command:

Variety of Front End Presets

In Laravel 5.3 and 5.4, we had some Vue and Bootstrap scaffolding by default to help us with the front-end bit. In this new version, React has been included in the mix. It’s not there by default though.

There is a new artisan command to manage the front-end presets. This means we’ll only have the scaffolding for the preset we want to work with. But then not everyone wants to use the default front-end presets – i.e. Vue, Bootstrap and React – and might opt for something else, maybe a different front-end framework. And Laravel has already taken that into consideration:

The above command will remove any existing front-end scaffolding. Had we wanted to use React for our front-end, the command below would get us some React scaffolding:

Nvidia 3d video controller driver. Below is a screenshot of this new command in action:

Whoops is Back!

Laravel 5.5 has brought Whoops! back, changing the way errors are displayed. With Whoops!, every time we have an error in development, we’ll be able to see the line of code that resulted in the error in the form of a screenshot as well as the error message.

In my opinion, error messages look better with this new handler and the fact that we get a screenshot with the line of code that resulted in the error makes debugging even easier:

Whoops error example:

Another cool thing is that Whoops comes with the ability to open referenced files directly in your IDE or editor. This feature only works in case your PHP-source files are locally accessible to the machine on which the editor is installed. To achieve this, head over to app/Exceptions/Handler.php and add this snippet:

appExceptionsHandler.php

The above snippet overrides the whoopsHandler() method from the base class by adding the line: $handler->setEditor('sublime'), which causes the link to open in Sublime Text. In case you are using a different editor, visit this link to see the list of supported editors and also how to add your own editor. Mac users, don’t forget to download the sublime URL protocol for this to work.

Custom Exception Report Method

For previous Laravel versions, if we wanted to handle custom exceptions thrown in a specific way, then we had to place our logic inside the report method of the Handler.php file. Below is an example:

app/Exceptions/Handler.php

Say we have about 50 custom exceptions – you can tell things are going to get ugly.

In Laravel 5.5, it’s possible to specify what happens when a custom exception is thrown by creating a report() method inside that exception:

app/Exceptions/CustomException.php

Model Factory Generators

Laravel 5.5 has introduced a new command to create a model factory. Model factories come in handy when we want to generate fake data or a new instance of an object when writing tests.

To generate a factory for a particular class, we run the command:

If we now navigate to database/factories, we’ll see a PostFactory class:

database/factories/PostFactory.php

I find this approach more elegant due to the separation of concerns. In previous Laravel versions, all factories went inside the app/factories/ModelFactory.php file.

Validation Data Return

It’s now possible to get data from the validator and pass it to the create method. In previous Laravel versions this is how we went about creating new objects:

Laravel 5.5 will now let us create objects directly from the validated data:

It’s also possible to call validate on a request instance directly in Laravel 5.5:

Note, however, we need to be careful when creating objects with this approach since any attribute that is left out from the validate method will not have a value. To counter this, we pass in all the attributes we want for the object to be created inside the validate method even if the values passed don’t need any validation:

With that, the field will automatically get added to the allowed request data, but not be restricted by any validation rules.

Custom Validation Rules

This was still possible in previous Laravel versions by using the Validator::extend method. However, things were not centralized. We had the rule go inside the AppServiceProvider file, then the message inside the resources/lang/en/validation.php file. See Laravel documentation on how to achieve this in Laravel 5.4.

In Laravel 5.5 we have a new artisan command to define custom validation. This command will generate a new class implementing the Rule contract. Let’s generate a new rule to see what’s inside this generated file:

If we look inside app/Rules/CustomRule.php, we see two methods i.e. the passes method and the message method. The passes method takes two arguments i.e. the attribute and the value, and returns a boolean. In case you are confused, the $attribute is the field to be validated while the $value is the actual value being passed to that attribute.

As an example, let’s say we didn’t want our app to take a certain name, then we’d have our Rule looking like this:

app/Rules/CustomRule.php

Then using the new rule to validate our username attribute:

app/Rules/CustomRule.php

See Taylor Otwell’s post which goes into depth on how to define custom validation in this new Laravel Version.

Laravel 5.5 Key Generator Download

DD and Dump Coming to Collections

Collections now have a dump() method as well as a dd() method. In previous Laravel versions, when debugging collections we’d assign a variable to a collection then keep dumping the variable as we altered the collection. This won’t be the case anymore in Laravel 5.5 as we can now call dd() or dump() directly on a collection making debugging a lot easier.

Assuming we had a collection of posts which went through a series of transformations and we wanted to inspect the collection at each step, then this will do:

And the output:

This makes it easy to inspect the contents of the collection at each step. Note, however, that there’s a difference between calling dump() and dd() on a collection. dump() outputs the results at that moment and then continues processing while dd() stops the process immediately and dumps out the results (dd stands for dump and die). Had we called dd() on the collection at every step, then we’d only get the results at the very first point when we called dd() on the collection. Consider this:

The output will be different:

Pivot Table Casting in Many to Many Relationships

Normally, it’s possible to declare a casts property on a Model which defines how an attribute should be saved or read. Let’s say we have a Post model and among the fields, we want one field to be serialized as JSON during reading and writing, then the code snippet below will help us achieve that:

They even made it possible to cast custom pivots in many-to-many relationships in Laravel 5.4, but this was limited to just reading data. Had we wanted to perform write operations on the data, we first had to cast the attribute values manually before finally saving. This won’t be the case anymore as the $casts property on the EloquentModel and EloquentRelationsPivot classes will behave the same making the attach, sync and save methods available to pivot models.

Custom Blade::if() Directives

Long repetitive checks within blade templates can make our templates ugly. The good news is that it’s now possible to abstract repetitive checks out of templates, leaving our templates looking cleaner and more readable. Checks like:

Can be substituted for:

The logic for creating a custom blade directive goes inside the boot method of the AppServiceProvider class:

app/Providers/AppServiceProvider.php

Some checks may require an argument be passed to some method. In that case, we pass in an argument to our closure when coming up with a custom blade directive.

Using the above conditional as an example, we see that we need the $user->id passed to the isFollowing() method. To create a custom blade directive which takes in the $user->id as an argument:

Then to use this new directive in our templates:

Autoregistering of New Artisan Commands in the Kernel

We usually run the command php artisam make:command command-name to create new artisan commands. After that, we declare our signature inside the class with the command then head over to the kernel and manually register the command.

Registering new commands in the Kernel won’t be a requirement anymore. Inside the app/Console/kernel.php file, we have a new method which looks within the command directory and turns all file paths into a namespaced path:

Assuming we referenced a command which has not yet been registered in the kernel, the commands() method will resolve the command automatically.

New Routing Methods

Not really a big feature but we now have two extra routing methods:

The first route will map the welcome view to the /welcome path while the second will redirect any requests made to /home to the /dashboard.

Laravel 5.5 Key Generate Download

Introducing Laravel Horizon

This is a new Laravel package which provides a dashboard and code-driven configuration system for Laravel Redis queues:

Horizon provides real-time insight into queue workloads, recent jobs, failed jobs, job retries, throughput and runtime metrics, and process counts.

Some of the features that come with Horizon include:

  • High-level analytics for jobs – Things like jobs per minute and jobs in the past hour
  • Job and queue specific analytics
  • Tags and monitoring – It’s possible to add tags to jobs and also monitor certain tags
  • Recent jobs – We can get information about the most recent jobs
  • Queue Balancing Strategies – Horizon can automatically balance your queue worker processes across your queues depending on the workload of those queues

See Taylor Otwell’s post which goes into depth on how to configure Horizon and all the features Horizon is packed with. We’ll have a dedicated Horizon post as well, so stay tuned.

New database migration trait

This is the RefreshDatabase trait. Some might wonder if we really need this, but the move behind coming up with this makes sense. Initially we had the DatabaseMigrations and DatabaseTransactions traits.

Using the DatabaseMigrations trait in our tests makes sure that migrations are run before and after each test, while the DatabaseTransactions trait ensures that the database is restored to its initial state after each test is run.

The RefreshDatabase trait will tap both capabilities by migrating the database once at the start of our tests and then running every test after that with transactions. The advantage of this is that we don’t have to re-migrate the database for each test, meaning faster tests.

Laravel 5.5 Key Generator For Sale

Conclusion

Serial Key Generator

As you can see, we have a lot of exciting new stuff. However, the official release has not yet happened, so we have to wait for the upgrade guide to be published.

Laravel 5.5 Key Generator Free

More features are still being rolled out so keep a keen eye on this post as we keep it up to date. Leave your thoughts and suggestions in the comments section below, and don’t forget to share this post with fellow Laravel enthusiasts!