Laravel Tutorial: Step by Step Guide to Building Your First Laravel Application
Since its initial release in 2011, Laravel has experienced exponential growth. In 2015, it became the most starred PHP framework on GitHub and rose to the go-to framework for people all over the world. If you’d like to learn more about the history, check out what is Laravel.
Laravel focuses on the end-user first: which means it focus is on simplicity, clarity, and getting work done. People and companies are using it to build everything from simple hobby projects all the way to Fortune 500 companies.
My goal with this Laravel tutorial to create a guide for those just learning Laravel. This guide will take you from the very beginning of an idea into a real deployable application. If you’d prefer to read this as an ebook you can join our weekly Laravel Newsletter and get it for free.
This look at Laravel will not be exhaustive, but if you want a more exhaustive introduction I recommend the book Laravel: Up and Running. This tutorial does expect a few prerequisites and here is what you will need to follow along:
- A local PHP environment (Valet, Homestead, Vagrant, MAMP, etc.).
- A database (I’ll be using MySQL)
- PHPUnit installed.
- Node JS installed.
Note: For the local PHP development I Recommend Mac OSX and Valet because it automatically sets everything up. If you are on Windows, consider Homestead or some flavor of a virtual machine. Another option is a community-provided Windows port of Valet.
I am attempting to go through the process of creating a new application just as I would in a real-world environment. In fact, the code and idea are from a project I built.
Mục Lục
Planning
Every project has to start somewhere; either a project assignment at work or just an idea in your head. No matter where it originates, thoroughly planning out all the features before you start coding is paramount in completing a project.
How you plan is dependent on how your mind works. As a visual person, I like to plan on paper, drawing out the way I picture the screens looking and then working backward into how I would code it. Others prefer to write a project plan in a text file, wiki, or some mind mapping tool. It doesn’t matter how you plan, just that you do it.
For this guide, we are going to be building a link directory. Here is a list of fundamental goals for this links app:
- Display a simple list of links.
- Create a form where people can submit new links.
- Validate the form.
- Insert the data into the database.
Let’s get started!
The First Steps
With a simple plan of attack outlined, it’s time to get a brand new empty project up and running. I like to put all my projects in a ~/Sites directory, and these instructions will use that location. I’ve already “parked” this directory in Valet, so any folders will automatically be mapped to “foldername.test” in the browser.
Open your terminal application and switch into this directory.
1
mkdir ~/Sites
2
cd ~/Sites
Laravel provides a convenient installer. If you’re planning on writing Laravel apps, follow the installation documentation for details on setting up the installer.
Whether you set up the installer or want to use composer, run one of the following to create a new Laravel project for the links
application:
1
# Via the installer
2
laravel new links
3
4
# Via composer
5
composer create-project --prefer-dist laravel/laravel links "7.*"
This will create a new directory at ~/Sites/links
and install a new Laravel project.
Visiting links.test
in the browser now shows the default Laravel welcome page:
Database Setup
When you create a new Laravel project, the installation process automatically creates a .env
file (copied from the .env.example
file) for configuration and credentials. Depending on your setup, you’ll need to modify the following block of settings to match your database configuration:
1
DB_CONNECTION
=
mysql
2
DB_HOST
=
127.0
.0.1
3
DB_PORT
=
3306
4
DB_DATABASE
=
laravel
5
DB_USERNAME
=
root
6
DB_PASSWORD
=
You may want to create a new database for this project:
1
# Connect via the mysql CLI
2
mysql -u root -p
3
mysql> create database links_development;
4
mysql> exit
5
6
# Or use the -e flag to run the create command
7
mysql -u root -e'create database links_development'
You would then want to adjust the database configuration in .env
:
1
DB_CONNECTION
=
mysql
2
DB_HOST
=
127.0
.0.1
3
DB_PORT
=
3306
4
DB_DATABASE
=
links_development
5
DB_USERNAME
=
root
6
DB_PASSWORD
=
The best way to test your database connection is running the migrate
artisan command:
1
php artisan migrate
If everything went according to plan, you should see something like the following after running the migrate command:
Authentication Scaffolding
Laravel has a separate first-party package for generating common scaffolding that makes setting up authentication a breeze. To use it, we need to install the UI composer package:
1
composer install laravel/ui
The UI package provides a few commands for setting up scaffolding for tools like React, Vue, and Bootstrap. We’ll create simple auth scaffolding for this project, but feel free to follow the frontend setup documentation.
Run the following to generate routes, controllers, views, and other files necessary for auth:
1
php artisan ui bootstrap --auth
Last, we need to compile our CSS UI with the following:
1
npm install
2
3
# Build dev assets
4
npm run dev
5
6
# Or use a watcher to automatically update changes
7
npm run watch
The watch
command will listen for files changes to JS and CSS files, and automatically update them. You probably want to have npm run watch
running in a separate tab while developing.
Even though this tutorial will not dive into authentication by running this command, it will modify our views and routes. So by doing it early, we don’t have to worry about it messing with any of our code.
With the basics set up and working, it’s time to start doing some coding.
Building a List of Links
If you start thinking about a finished project, it’s easy to get overwhelmed. The best way to fight this is to break the project down into small tasks. So, let’s start by showing a list of links.
Even though showing a list of links sounds like a small task it still requires a database, a database table, data in the table, a database query, and a view file.
Creating a migration will be the first step, and the Laravel Artisan command line tool can help us build that.
1
php artisan make:migration create_links_table --create=links
Now, open the file this command created. It will be located at database/migrations/{{datetime}}_create_links_table.php. You’ll notice a few other migrations in this folder as well, which the framework provides.
Inside the “up()” method, add the following schema:
1
Schema
::
create
(
'links'
,
function
(
Blueprint
$table) {
2
$table
->
increments
(
'id'
);
3
$table
->
string
(
'title'
);
4
$table
->
string
(
'url'
)
->
unique
();
5
$table
->
text
(
'description'
);
6
$table
->
timestamps
();
7
});
Save the file and run the migration:
1
php artisan migrate
While you are working with test data, you can quickly apply the schema:
1
php artisan migrate:fresh
Next, we need some data and a model to work with our database table. Laravel provides two features to help with this, the first is a database seeder, which populates the database with data, and second, the model factory files that allow us to generate fake model data that we can use to fill our development database and tests:
1
php artisan make:model --factory Link
The make:model
command creates an app/Link.php
model file. Laravel models provide a powerful database API called Eloquent, which you can explore in great detail in the Eloquent documentation.
The --factory
flag will generate a new factory file in the database/factories
path for generating app data. In our case, a new LinkFactory
file will include an empty factory definition for our Link
model.
Open the LinkFactory.php
file and fill in the following:
1
<?php
2
3
/**
@var
\Illuminate\Database\Eloquent\Factory
$factory */
4
5
use
App\Link
;
6
use
Faker\Generator
as
Faker
;
7
8
$factory
->
define
(
Link
::class
,
function
(
Faker
$faker) {
9
return
[
10
'title'
=>
substr
($faker
->
sentence
(
2
),
0
,
-
1
),
11
'url'
=>
$faker
->
url,
12
'description'
=>
$faker
->
paragraph,
13
];
14
});
We use the $faker->sentence()
method to generate a title, and substr
to remove the period at the end of the sentence.
Next, create the link seeder, so we can easily add demo data to the table:
1
php artisan make:seeder LinksTableSeeder
The make:seeder
command generates a new database class to seed our links
table with data.
Open the database/seeds/LinksTableSeeder.php
file and add the following:
1
public
function
run
()
2
{
3
factory
(
App\Link
::class
,
5
)
->
create
();
4
}
In order to “activate” the LinksTableSeeder
, we need to call it from the main database/seeds/DatabaseSeeder.php
run method:
1
public
function
run
()
2
{
3
$this
->
call
(
LinksTableSeeder
::class
);
4
}
You can now run the migrations and seeds to add data to the table automatically. Using the migrate:fresh
command, we can get a clean schema that applies all migrations and then seeds the database:
1
$ php artisan migrate:fresh --seed
2
Dropped all tables successfully.
3
Migration table created successfully.
4
Migrating: 2014_10_12_000000_create_users_table
5
Migrated: 2014_10_12_000000_create_users_table
6
Migrating: 2014_10_12_100000_create_password_resets_table
7
Migrated: 2014_10_12_100000_create_password_resets_table
8
Migrating: 2017_11_03_023418_create_links_table
9
Migrated: 2017_11_03_023418_create_links_table
10
Seeding: LinksTableSeeder
Using the tinker shell you can start playing around with the model data:
1
$ php artisan tinker
2
>>> \App\Link::first();
3
=> App\Link {#3060
4
id: 1,
5
title: "Rerum doloremque",
6
url: "http://russel.info/suscipit-et-iste-debitis-beatae-repudiandae-eveniet.html",
7
description: "Dolorem voluptas voluptatum voluptatem consequuntur amet dolore odit. Asperiores ullam alias vel soluta ut in. Facere quia et sit laudantium culpa ea possimus.",
8
created_at: "2020-04-05 00:44:33",
9
updated_at: "2020-04-05 00:44:33",
10
}
11
>>>
We have the data place and a model to interact with the database! Let’s start building the UI to add new links to the application.
Routing and Views
To build out a view showing the list of links, we need to update the main project route and also define a new route that will display our submission form. We can add new routes to our application in the routes/web.php
file.
In the web routes file you should see the default route below:
1
Route
::
get
(
'/'
,
function
() {
2
return
view
(
'welcome'
);
3
});
To create a new route, we can either use a route closure or a dedicated controller class. In this tutorial, we will use closures for our submission and index routes.
First, let’s update the home route by getting a collection of links from the database and passing them to the view:
1
Route
::
get
(
'/'
,
function
() {
2
$links
=
\App\Link
::
all
();
3
4
return
view
(
'welcome'
, [
'links'
=>
$links]);
5
});
The second argument can be an associative array of data, and the key ends up being the variable name in the template file.
You can also use a fluent API to define variables if you prefer:
1
// with()
2
return
view
(
'welcome'
)
->
with
(
'links'
, $links);
3
4
// dynamic method to name the variable
5
return
view
(
'welcome'
)
->
withLinks
($links);
Next, edit the welcome.blade.php file and add a simple foreach
to show all the links:
1
@foreach ($links as $link)
2
<a href="{{ $link->url }}">{{ $link->title }}</a>
3
@endforeach
Here’s what the welcome.blade.php
HTML should look like:
1
<body>
2
<div class="flex-center position-ref full-height">
3
@if (Route::has('login'))
4
<div class="top-right links">
5
@auth
6
<a href="{{ url('/home') }}">Home</a>
7
@else
8
<a href="{{ route('login') }}">Login</a>
9
<a href="{{ route('register') }}">Register</a>
10
@endauth
11
</div>
12
@endif
13
14
<div class="content">
15
<div class="title m-b-md">
16
Laravel
17
</div>
18
19
<div class="links">
20
@foreach ($links as $link)
21
<a href="{{ $link->url }}">{{ $link->title }}</a>
22
@endforeach
23
</div>
24
</div>
25
</div>
26
</body>
If you refresh your browser, you should now see the list of all the links added. With that all set, let’s move to submitting links.
Displaying the Link Submission Form
We are almost done creating our first application in Laravel!
We will round out this Laravel tutorial with the ability for others to submit links into the app, which requires three fields: title, URL, and a description.
I am a visual person, and before planning out features requiring HTML, I like to draw them out so I can get an idea of what I’m building in my head. Here is a simple drawing of this form:
Since we’ve added all the core structure, model factory, migration, and model, in the last section, we can reap the benefits by reusing all those for this section.
First, create a new route in the routes/web.php file:
1
Route
::
get
(
'/submit'
,
function
() {
2
return
view
(
'submit'
);
3
});
Next, we need to create the submit.blade.php
template at resources/views/submit.blade.php
with the following boilerplate bootstrap markup:
1
@extends
(
'layouts.app'
)
2
@section
(
'content'
)
3
<
div
class
=
"container"
>
4
<
div
class
=
"row"
>
5
<
h1
>Submit a link</
h1
>
6
</
div
>
7
<
div
class
=
"row"
>
8
<
form
action
=
"/submit"
method
=
"post"
>
9
@csrf
10
@if
($errors
->
any
())
11
<
div
class
=
"alert alert-danger"
role
=
"alert"
>
12
Please fix the following errors
13
</
div
>
14
@endif
15
<
div
class
=
"form-group"
>
16
<
label
for
=
"title"
>Title</
label
>
17
<
input
type
=
"text"
class
=
"form-control
@error
('title') is-invalid
@enderror
"
id
=
"title"
name
=
"title"
placeholder
=
"Title"
value
=
"
{{
old
(
'title'
)
}}
"
>
18
@error
(
'title'
)
19
<
div
class
=
"invalid-feedback"
>
{{
$message
}}
</
div
>
20
@enderror
21
</
div
>
22
<
div
class
=
"form-group"
>
23
<
label
for
=
"url"
>Url</
label
>
24
<
input
type
=
"text"
class
=
"form-control
@error
('url') is-invalid
@enderror
"
id
=
"url"
name
=
"url"
placeholder
=
"URL"
value
=
"
{{
old
(
'url'
)
}}
"
>
25
@error
(
'url'
)
26
<
div
class
=
"invalid-feedback"
>
{{
$message
}}
</
div
>
27
@enderror
28
</
div
>
29
<
div
class
=
"form-group"
>
30
<
label
for
=
"description"
>Description</
label
>
31
<
textarea
class
=
"form-control
@error
('description') is-invalid
@enderror
"
id
=
"description"
name
=
"description"
placeholder
=
"description"
>
{{
old
(
'description'
)
}}
</
textarea
>
32
@error
(
'description'
)
33
<
div
class
=
"invalid-feedback"
>
{{
$message
}}
</
div
>
34
@enderror
35
</
div
>
36
<
button
type
=
"submit"
class
=
"btn btn-primary"
>Submit</
button
>
37
</
form
>
38
</
div
>
39
</
div
>
40
@endsection
There’s quite a bit going on in this form, so let’s go over the major points that might be confusing when you are new to Laravel.
Near the top of the form, we have a blade conditional that checks to see if there are any validation errors. When errors exist, the bootstrap alert message will be shown, prompting the user to fix the invalid form fields:
1
@if
($errors
->
any
())
2
<
div
class
=
"alert alert-danger"
role
=
"alert"
>
3
Please fix the following errors
4
</
div
>
5
@endif
Each individual form field checks for validation errors and displays an error message and outputs a has-error
class:
1
<
div
class
=
"form-group"
>
2
<
label
for
=
"title"
>Title</
label
>
3
<
input
type
=
"text"
class
=
"form-control
@error
('title') is-invalid
@enderror
"
id
=
"title"
name
=
"title"
placeholder
=
"Title"
value
=
"
{{
old
(
'title'
)
}}
"
>
4
@error
(
'title'
)
5
<
div
class
=
"invalid-feedback"
>
{{
$message
}}
</
div
>
6
@enderror
7
</
div
>
If the user submits invalid data, the route will store validation in the session and redirect the user back to the form. The {{ old('title') }}
function will populate the originally submitted data. If a user forgot to submit one of the fields, the other fields that have data would be populated after validation fails and errors are shown.
If a field has an error, the @error
directive provides an error message variable you can use within the directive block:
1
@error
(
'title'
)
2
<
div
class
=
"invalid-feedback"
>
{{
$message
}}
</
div
>
3
@enderror
Another way to check and dispay errors involves the $error
variable provided to the view after a validation failure and redirect:
1
@if
($errors
->
has
(
'title'
))
2
<
div
class
=
"invalid-feedback"
>
{{
$errors
->
first
(
'title'
)
}}
</
div
>
3
@endif
The @error
directive uses the same variable under the hood, feel free to use whichever method you prefer.
Submitting the Form
With the form in place, we are ready to handle sending and validating form data on the server. Back in the routes/web.php
file, create another route for the POST
request:
1
use
Illuminate\Http\Request
;
2
3
Route
::
post
(
'/submit'
,
function
(
Request
$request) {
4
$data
=
$request
->
validate
([
5
'title'
=>
'required|max:255'
,
6
'url'
=>
'required|url|max:255'
,
7
'description'
=>
'required|max:255'
,
8
]);
9
10
$link
=
tap
(
new
App\Link
($data))
->
save
();
11
12
return
redirect
(
'/'
);
13
});
Note: make sure you add use Illuminate\Http\Request
near the top of web.php
.
This route is a little more complicated than the others.
First, we are injecting the Illuminate\Http\Request object, which holds the POST data and other data about the request.
Next, we use the request’s validate()
method to validate the form data. The validate method was introduced in Laravel 5.5 and is a nice shortcut over other methods used for validation. As a bonus, the validated fields are returned to the $data
variable, and we can use them to populate our model.
We require all three fields, and using the pipe character we can define multiple rules. All three rules can have a max of 255 characters, and the url
field requires a valid URL.
If validation fails, an exception is thrown, and the route returns the user with the original input data and validation errors.
Next, we use the tap()
helper function to create a new Link
model instance and then save it. Using tap allows us to call save()
and still return the model instance after the save.
Typically, you would have to do the following without tap, it just adds a little syntactic sugar:
1
$link
=
new
\App\Link
($data);
2
$link
->
save
();
3
4
return
$link;
If we want to populate a new model with data, we need to allow the fields to be “fillable” via mass assignment. The fillable property is designed to prevent fields from being mass-assigned except for the items you define in the array.
Think about this for a minute: we are taking user input from the request and mass assigning the values on the database model. Be aware of the dangers of user-submitted data and take care to guard against data you don’t intend the user to directly manipulate via a form.
In our case, we are validating each field so allowing them to be mass-assigned is safe. To allow our model to assign values to these fields, open the app/Link.php
file and update it to look like the following:
1
<?php
2
3
namespace
App
;
4
5
use
Illuminate\Database\Eloquent\Model
;
6
7
class
Link
extends
Model
8
{
9
protected
$fillable
=
[
10
'title'
,
11
'url'
,
12
'description'
13
];
14
}
If we wanted to avoid mass-assignment, this is how our code might look:
1
$data
=
$request
->
validate
([
2
'title'
=>
'required|max:255'
,
3
'url'
=>
'required|url|max:255'
,
4
'description'
=>
'required|max:255'
,
5
]);
6
7
$link
=
new
\App\Link
;
8
$link
->
title
=
$data[
'title'
];
9
$link
->
url
=
$data[
'url'
];
10
$link
->
description
=
$data[
'description'
];
11
12
// Save the model
13
$link
->
save
();
The last thing we do in our POST route redirects the user back to the home page after saving the link successfully.
At this point, our form should prevent submitting links with invalid fields:
If the form passes validation, the data should be saved in the database and the user redirect back to the homepage.
Testing the Form Submission
We have a basic working form, but we should make sure it continues to work by writing tests.
Laravel makes HTTP testing a breeze for performing integration tests against routes and middleware, so let’s write a few feature tests to verify our code works as expected.
Before we get started, we need to adjust a few things in our phpunit.xml
file so that we can use an in-memory SQLite database. You will need to make sure that you have the proper PHP modules installed.
As of Laravel 7, the project’s phpunit.xml
file configures an in-memory SQLite database. If you’re using an older version of Laravel, change the database connection by adding the following:
1
<
php
>
2
<!-- ... -->
3
<
env
name
=
"DB_CONNECTION"
value
=
"sqlite"
/>
4
<
env
name
=
"DB_DATABASE"
value
=
":memory:"
/>
5
<!-- ... -->
6
</
php
>
Next, remove the placeholder test that ships with Laravel:
1
rm tests/Feature/ExampleTest.php
We are ready to start testing the /submit
form through HTTP requests to make sure that the route validation, saving, and redirecting are working as expected.
First, let’s create a new feature test to test against our route:
1
php artisan make:test SubmitLinksTest
The command creates a new testing file with the proper dependencies, including a RefreshDatabase
trait that we are going to use to verify that our links are being saved to the database when valid.
Open the new tests/Feature/SubmitLinksTest.php
file and let’s define a few skeleton tests in the body of the class that we are going to flesh out:
1
/** @test */
2
function
guest_can_submit_a_new_link
() {}
3
4
/** @test */
5
function
link_is_not_created_if_validation_fails
() {}
6
7
/** @test */
8
function
link_is_not_created_with_an_invalid_url
() {}
9
10
/** @test */
11
function
max_length_fails_when_too_long
() {}
12
13
/** @test */
14
function
max_length_succeeds_when_under_max
() {}
These tests should give you a high-level overview of what we are going to test:
- Verify that valid links get saved in the database
- When validation fails, links are not in the database
- Invalid URLs are not allowed
- Validation should fail when the fields are longer than the
max:255
validation rule - Validation should succeed when the fields are long enough according to
max:255
.
We might be missing some things, but for your first Laravel application, this is a decent list that should illustrate some basic HTTP testing techniques in Laravel.
Saving a valid link
The first test we’ll write is the test that verifies that valid data gets stored in the database:
1
<?php
2
3
namespace
Tests\Feature
;
4
5
use
Illuminate\Validation\ValidationException
;
6
use
Tests\TestCase
;
7
use
Illuminate\Foundation\Testing\RefreshDatabase
;
8
9
class
SubmitLinksTest
extends
TestCase
10
{
11
use
RefreshDatabase
;
12
13
/** @test */
14
function
guest_can_submit_a_new_link
()
15
{
16
$response
=
$this
->
post
(
'/submit'
, [
17
'title'
=>
'Example Title'
,
18
'url'
=>
'http://example.com'
,
19
'description'
=>
'Example description.'
,
20
]);
21
22
$this
->
assertDatabaseHas
(
'links'
, [
23
'title'
=>
'Example Title'
24
]);
25
26
$response
27
->
assertStatus
(
302
)
28
->
assertHeader
(
'Location'
,
url
(
'/'
));
29
30
$this
31
->
get
(
'/'
)
32
->
assertSee
(
'Example Title'
);
33
}
34
}
Take note of the RefreshDatabase
trait which makes sure that each test has a new database to give each test a pristine database environment with all the migrations.
Our first test submits valid post data, which returns a response object that we can use to assert that our route responded as expected. We verify that the database contains a record with the title we just created.
Next, we verify that the response was a 302
status code with a Location
header pointing to the homepage.
Last, we request the home page and verify that the link title is visible on the homepage.
Let’s run our first test to make sure things pass as expected. Laravel 7 adds a new artisan test
command, or you can use phpunit
:
1
php artisan test
2
3
# Or run phpunit directly
4
vendor/bin/phpunit
You should see that the test suite passes:
Testing Failed Validation
When a user generally submits bad data, we expect the validation to trigger an exception and we can use that to make sure our validation layer is working:
1
/** @test */
2
function
link_is_not_created_if_validation_fails
()
3
{
4
$response
=
$this
->
post
(
'/submit'
);
5
6
$response
->
assertSessionHasErrors
([
'title'
,
'url'
,
'description'
]);
7
}
We use Laravel’s assertSessionHasErrors()
to make sure that the session has validation errors for each of our required fields. Because we submitted empty data to the route, we expect the required
rule will trigger for each field.
Let’s run the test suite to verify our work thus far:
1
$ php artisan test tests/Feature/SubmitLinksTest
2
3
PASS Tests\Feature\SubmitLinksTest
4
✓ guest can submit a new link
5
✓ link is not created if validation fails
6
7
Tests: 2 passed
8
Time: 0.32s
Testing URL Validation
We expect only valid URLs to pass validation so that our application doesn’t try to display invalid data.
1
/** @test */
2
function
link_is_not_created_with_an_invalid_url
()
3
{
4
$this
->
withoutExceptionHandling
();
5
6
$cases
=
[
'//invalid-url.com'
,
'/invalid-url'
,
'foo.com'
];
7
8
foreach
($cases
as
$case) {
9
try
{
10
$response
=
$this
->
post
(
'/submit'
, [
11
'title'
=>
'Example Title'
,
12
'url'
=>
$case,
13
'description'
=>
'Example description'
,
14
]);
15
}
catch
(
ValidationException
$e) {
16
$this
->
assertEquals
(
17
'The url format is invalid.'
,
18
$e
->
validator
->
errors
()
->
first
(
'url'
)
19
);
20
continue
;
21
}
22
23
$this
->
fail
(
"The URL
$case
passed validation when it should have failed."
);
24
}
25
}
Laravel has a withoutExceptionHandling()
method which disables Laravel’s route exception handling code used to generate an HTTP response after an exception. We use this to our advantage so we can inspect the validation exception object and assert against the error messages.
We loop through various cases (add your own if you’d like to cover more scenarios) and catch instances of ValidationException
. If the text makes it past the exception handling, we manually fail the test because we expect the route throws a ValidationExcepiton
exception each time.
The catch
block uses the validator object to check the url
error and asserts that the actual error message matches the expected validation error message.
I like using the try/catch
technique, followed by a $this->fail()
as a safety harness instead of using exception annotations provided by PHPUnit. Be sure to return
in the caught exception to avoid confusing test failures. I feel catching the exception allows the ability to do assertions that wouldn’t otherwise be possible and provides a more granular control that I like in most cases.
Testing Max Length Validation
We will test a few scenarios with the max:255
validations rules: when the field fails max-length validation with a length of 256
characters, and when the field is long enough to pass validation at 255
characters.
Although Laravel contains the max
validation rule functionality, I like to test it to verify that my application applies the rules. If someone removes the max
validation rule, then the tests will catch it.
I like to test the threshold of min and max validation rules as an extra caution to make sure my application respects the min and max boundaries I set.
First, let’s test the “max length” scenario:
1
/** @test */
2
function
max_length_fails_when_too_long
()
3
{
4
$this
->
withoutExceptionHandling
();
5
6
$title
=
str_repeat
(
'a'
,
256
);
7
$description
=
str_repeat
(
'a'
,
256
);
8
$url
=
'http://'
;
9
$url
.=
str_repeat
(
'a'
,
256
-
strlen
($url));
10
11
try
{
12
$this
->
post
(
'/submit'
,
compact
(
'title'
,
'url'
,
'description'
));
13
}
catch
(
ValidationException
$e) {
14
$this
->
assertEquals
(
15
'The title may not be greater than 255 characters.'
,
16
$e
->
validator
->
errors
()
->
first
(
'title'
)
17
);
18
19
$this
->
assertEquals
(
20
'The url may not be greater than 255 characters.'
,
21
$e
->
validator
->
errors
()
->
first
(
'url'
)
22
);
23
24
$this
->
assertEquals
(
25
'The description may not be greater than 255 characters.'
,
26
$e
->
validator
->
errors
()
->
first
(
'description'
)
27
);
28
29
return
;
30
}
31
32
$this
->
fail
(
'Max length should trigger a ValidationException'
);
33
}
Again, we disable exception handling and create data that is one character too long to pass validation.
We assert each field to make sure they all have a max length validation error message.
Last, we need to return
in the caught exception and use the $this->fail()
as a safety harness to fail the test.
Next, we test the “under the max” scenario:
1
/** @test */
2
function
max_length_succeeds_when_under_max
()
3
{
4
$url
=
'http://'
;
5
$url
.=
str_repeat
(
'a'
,
255
-
strlen
($url));
6
7
$data
=
[
8
'title'
=>
str_repeat
(
'a'
,
255
),
9
'url'
=>
$url,
10
'description'
=>
str_repeat
(
'a'
,
255
),
11
];
12
13
$this
->
post
(
'/submit'
, $data);
14
15
$this
->
assertDatabaseHas
(
'links'
, $data);
16
}
We make the form data long enough to pass max:255
validation and assert that the data is in the database after submitting the data.
Run the test suite and make sure everything is passing:
1
$ php artisan test tests/Feature/SubmitLinksTest
2
3
PASS Tests\Feature\SubmitLinksTest
4
✓ guest can submit a new link
5
✓ link is not created if validation fails
6
✓ link is not created with an invalid url
7
✓ max length fails when too long
8
✓ max length succeeds when under max
9
10
Tests: 5 passed
11
Time: 0.58s
Conclusion
Congratulations on making it through the tutorial!
This guide was designed to get you started on building your app, and you can use this as a building block to gain the skills you need to develop your application. I know this covers a lot of features and can be overwhelming if you are not familiar with the framework.
I hope this introduction to Laravel shows you why so many people are excited about the framework.
Join the weekly newsletter and check out the Laravel tutorials section of the site to go deeper and learn even more about Laravel.