Basic Task List

Introduction

This quickstart guide provides a basic introduction to the Laravel framework and includes content on database migrations, the Eloquent ORM, routing, validation, views, and Blade templates. This is a great starting point if you are brand new to the Laravel framework or PHP frameworks in general. If you have already used Laravel or other PHP frameworks, you may wish to consult one of our more advanced quickstarts.

To sample a basic selection of Laravel features, we will build a simple task list we can use to track all of the tasks we want to accomplish. In other words, the typical "to-do" list example. The complete, finished source code for this project is available on GitHub.

Installation

Installing Laravel

Of course, first you will need a fresh installation of the Laravel framework. You may use the Homestead virtual machine or the local PHP environment of your choice to run the framework. Once your local environment is ready, you may install the Laravel framework using Composer:

  1. composer create-project laravel/laravel quickstart --prefer-dist

Installing The Quickstart (Optional)

You're free to just read along for the remainder of this quickstart; however, if you would like to download the source code for this quickstart and run it on your local machine, you may clone its Git repository and install its dependencies:

  1. git clone https://github.com/laravel/quickstart-basic quickstart
  2. cd quickstart
  3. composer install
  4. php artisan migrate

For more complete documentation on building a local Laravel development environment, check out the full Homestead and installation documentation.

Prepping The Database

Database Migrations

First, let's use a migration to define a database table to hold all of our tasks. Laravel's database migrations provide an easy way to define your database table structure and modifications using fluent, expressive PHP code. Instead of telling your team members to manually add columns to their local copy of the database, your teammates can simply run the migrations you push into source control.

So, let's build a database table that will hold all of our tasks. The Artisan CLI can be used to generate a variety of classes and will save you a lot of typing as you build your Laravel projects. In this case, let's use the make:migration command to generate a new database migration for our tasks table:

  1. php artisan make:migration create_tasks_table --create=tasks

The migration will be placed in the database/migrations directory of your project. As you may have noticed, the make:migration command already added an auto-incrementing ID and timestamps to the migration file. Let's edit this file and add an additional string column for the name of our tasks:

  1. <?php
  2. use Illuminate\Database\Schema\Blueprint;
  3. use Illuminate\Database\Migrations\Migration;
  4. class CreateTasksTable extends Migration
  5. {
  6. /**
  7. * Run the migrations.
  8. *
  9. * @return void
  10. */
  11. public function up()
  12. {
  13. Schema::create('tasks', function (Blueprint $table) {
  14. $table->increments('id');
  15. $table->string('name');
  16. $table->timestamps();
  17. });
  18. }
  19. /**
  20. * Reverse the migrations.
  21. *
  22. * @return void
  23. */
  24. public function down()
  25. {
  26. Schema::drop('tasks');
  27. }
  28. }

To run our migration, we will use the migrate Artisan command. If you are using Homestead, you should run this command from within your virtual machine, since your host machine will not have direct access to the database:

  1. php artisan migrate

This command will create all of our database tables. If you inspect the database tables using the database client of your choice, you should see a new tasks table which contains the columns defined in our migration. Next, we're ready to define an Eloquent ORM model for our tasks!

Eloquent Models

Eloquent is Laravel's default ORM (object-relational mapper). Eloquent makes it painless to retrieve and store data in your database using clearly defined "models". Usually, each Eloquent model corresponds directly with a single database table.

So, let's define a Task model that corresponds to our tasks database table we just created. Again, we can use an Artisan command to generate this model. In this case, we'll use the make:model command:

  1. php artisan make:model Task

The model will be placed in the app directory of your application. By default, the model class is empty. We do not have to explicitly tell the Eloquent model which table it corresponds to because it will assume the database table is the plural form of the model name. So, in this case, the Task model is assumed to correspond with the tasks database table. Here is what our empty model should look like:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Task extends Model
  5. {
  6. //
  7. }

We'll learn more about how to use Eloquent models as we add routes to our application. Of course, feel free to consult the complete Eloquent documentation for more information.

Routing

Stubbing The Routes

Next, we're ready to add a few routes to our application. Routes are used to point URLs to controllers or anonymous functions that should be executed when a user accesses a given page. By default, all Laravel routes are defined in the app/Http/routes.php file that is included in every new project.

For this application, we know we will need at least three routes: a route to display a list of all of our tasks, a route to add new tasks, and a route to delete existing tasks. So, let's stub all of these routes in the app/Http/routes.php file:

  1. <?php
  2. use App\Task;
  3. use Illuminate\Http\Request;
  4. /**
  5. * Show Task Dashboard
  6. */
  7. Route::get('/', function () {
  8. //
  9. });
  10. /**
  11. * Add New Task
  12. */
  13. Route::post('/task', function (Request $request) {
  14. //
  15. });
  16. /**
  17. * Delete Task
  18. */
  19. Route::delete('/task/{task}', function (Task $task) {
  20. //
  21. });

Note: If your copy of Laravel has a RouteServiceProvider that already includes the default routes file within the web middleware group, you do not need to manually add the group to your routes.php file.

Displaying A View

Next, let's fill out our / route. From this route, we want to render an HTML template that contains a form to add new tasks, as well as a list of all current tasks.

In Laravel, all HTML templates are stored in the resources/views directory, and we can use the view helper to return one of these templates from our route:

  1. Route::get('/', function () {
  2. return view('tasks');
  3. });

Passing tasks to the view function will create a View object instance that corresponds to the template in resources/views/tasks.blade.php. Of course, we need to actually define this view, so let's do that now!

Building Layouts & Views

This application only has a single view which contains a form for adding new tasks as well as a listing of all current tasks. To help you visualize the view, here is a screenshot of the finished application with basic Bootstrap CSS styling applied:

Application Image

Defining The Layout

Almost all web applications share the same layout across pages. For example, this application has a top navigation bar that would be typically present on every page (if we had more than one). Laravel makes it easy to share these common features across every page using Blade layouts.

As we discussed earlier, all Laravel views are stored in resources/views. So, let's define a new layout view in resources/views/layouts/app.blade.php. The .blade.php extension instructs the framework to use the Blade templating engine to render the view. Of course, you may use plain PHP templates with Laravel. However, Blade provides convenient short-cuts for writing clean, terse templates.

Our app.blade.php view should look like the following:

  1. <!-- resources/views/layouts/app.blade.php -->
  2. <!DOCTYPE html>
  3. <html lang="en">
  4. <head>
  5. <title>Laravel Quickstart - Basic</title>
  6. <!-- CSS And JavaScript -->
  7. </head>
  8. <body>
  9. <div class="container">
  10. <nav class="navbar navbar-default">
  11. <!-- Navbar Contents -->
  12. </nav>
  13. </div>
  14. @yield('content')
  15. </body>
  16. </html>

Note the @yield('content') portion of the layout. This is a special Blade directive that specifies where all child pages that extend the layout can inject their own content. Next, let's define the child view that will use this layout and provide its primary content.

Defining The Child View

Next, we need to define a view that contains a form to create a new task as well as a table that lists all existing tasks. Let's define this view in resources/views/tasks.blade.php.

We'll skip over some of the Bootstrap CSS boilerplate and only focus on the things that matter. Remember, you can download the full source for this application on GitHub:

  1. <!-- resources/views/tasks.blade.php -->
  2. @extends('layouts.app')
  3. @section('content')
  4. <!-- Bootstrap Boilerplate... -->
  5. <div class="panel-body">
  6. <!-- Display Validation Errors -->
  7. @include('common.errors')
  8. <!-- New Task Form -->
  9. <form action="{{ url('task') }}" method="POST" class="form-horizontal">
  10. {{ csrf_field() }}
  11. <!-- Task Name -->
  12. <div class="form-group">
  13. <label for="task" class="col-sm-3 control-label">Task</label>
  14. <div class="col-sm-6">
  15. <input type="text" name="name" id="task-name" class="form-control">
  16. </div>
  17. </div>
  18. <!-- Add Task Button -->
  19. <div class="form-group">
  20. <div class="col-sm-offset-3 col-sm-6">
  21. <button type="submit" class="btn btn-default">
  22. <i class="fa fa-plus"></i> Add Task
  23. </button>
  24. </div>
  25. </div>
  26. </form>
  27. </div>
  28. <!-- TODO: Current Tasks -->
  29. @endsection

A Few Notes Of Explanation

Before moving on, let's talk about this template a bit. First, the @extends directive informs Blade that we are using the layout we defined in resources/views/layouts/app.blade.php. All of the content between @section('content') and @endsection will be injected into the location of the @yield('content') directive within the app.blade.php layout.

The @include('common.errors') directive will load the template located at resources/views/common/errors.blade.php. We haven't defined this template, but we will soon!

Now we have defined a basic layout and view for our application. Remember, we are returning this view from our / route like so:

  1. Route::get('/', function () {
  2. return view('tasks');
  3. });

Next, we're ready to add code to our POST /task route to handle the incoming form input and add a new task to the database.

Adding Tasks

Validation

Now that we have a form in our view, we need to add code to our POST /task route in app/Http/routes.php to validate the incoming form input and create a new task. First, let's validate the input.

For this form, we will make the name field required and state that it must contain less than 255 characters. If the validation fails, we will redirect the user back to the / URL, as well as flash the old input and errors into the session. Flashing the input into the session will allow us to maintain the user's input even when there are validation errors:

  1. Route::post('/task', function (Request $request) {
  2. $validator = Validator::make($request->all(), [
  3. 'name' => 'required|max:255',
  4. ]);
  5. if ($validator->fails()) {
  6. return redirect('/')
  7. ->withInput()
  8. ->withErrors($validator);
  9. }
  10. // Create The Task...
  11. });

The $errors Variable

Let's take a break for a moment to talk about the ->withErrors($validator) portion of this example. The ->withErrors($validator) call will flash the errors from the given validator instance into the session so that they can be accessed via the $errors variable in our view.

Remember that we used the @include('common.errors') directive within our view to render the form's validation errors. The common.errors will allow us to easily show validation errors in the same format across all of our pages. Let's define the contents of this view now:

  1. <!-- resources/views/common/errors.blade.php -->
  2. @if (count($errors) > 0)
  3. <!-- Form Error List -->
  4. <div class="alert alert-danger">
  5. <strong>Whoops! Something went wrong!</strong>
  6. <br><br>
  7. <ul>
  8. @foreach ($errors->all() as $error)
  9. <li>{{ $error }}</li>
  10. @endforeach
  11. </ul>
  12. </div>
  13. @endif

Note: The $errors variable is available in every Laravel view. It will simply be an empty instance of ViewErrorBag if no validation errors are present.

Creating The Task

Now that input validation is handled, let's actually create a new task by continuing to fill out our route. Once the new task has been created, we will redirect the user back to the / URL. To create the task, we may use the save method after creating and setting properties on a new Eloquent model:

  1. Route::post('/task', function (Request $request) {
  2. $validator = Validator::make($request->all(), [
  3. 'name' => 'required|max:255',
  4. ]);
  5. if ($validator->fails()) {
  6. return redirect('/')
  7. ->withInput()
  8. ->withErrors($validator);
  9. }
  10. $task = new Task;
  11. $task->name = $request->name;
  12. $task->save();
  13. return redirect('/');
  14. });

Great! We can now successfully create tasks. Next, let's continue adding to our view by building a list of all existing tasks.

Displaying Existing Tasks

First, we need to edit our / route to pass all of the existing tasks to the view. The view function accepts a second argument which is an array of data that will be made available to the view, where each key in the array will become a variable within the view:

  1. Route::get('/', function () {
  2. $tasks = Task::orderBy('created_at', 'asc')->get();
  3. return view('tasks', [
  4. 'tasks' => $tasks
  5. ]);
  6. });

Once the data is passed, we can spin through the tasks in our tasks.blade.php view and display them in a table. The @foreach Blade construct allows us to write concise loops that compile down into blazing fast plain PHP code:

  1. @extends('layouts.app')
  2. @section('content')
  3. <!-- Create Task Form... -->
  4. <!-- Current Tasks -->
  5. @if (count($tasks) > 0)
  6. <div class="panel panel-default">
  7. <div class="panel-heading">
  8. Current Tasks
  9. </div>
  10. <div class="panel-body">
  11. <table class="table table-striped task-table">
  12. <!-- Table Headings -->
  13. <thead>
  14. <th>Task</th>
  15. <th>&nbsp;</th>
  16. </thead>
  17. <!-- Table Body -->
  18. <tbody>
  19. @foreach ($tasks as $task)
  20. <tr>
  21. <!-- Task Name -->
  22. <td class="table-text">
  23. <div>{{ $task->name }}</div>
  24. </td>
  25. <td>
  26. <!-- TODO: Delete Button -->
  27. </td>
  28. </tr>
  29. @endforeach
  30. </tbody>
  31. </table>
  32. </div>
  33. </div>
  34. @endif
  35. @endsection

Our task application is almost complete. But, we have no way to delete our existing tasks when they're done. Let's add that next!

Deleting Tasks

Adding The Delete Button

We left a "TODO" note in our code where our delete button is supposed to be. So, let's add a delete button to each row of our task listing within the tasks.blade.php view. We'll create a small single-button form for each task in the list. When the button is clicked, a DELETE /task request will be sent to the application:

  1. <tr>
  2. <!-- Task Name -->
  3. <td class="table-text">
  4. <div>{{ $task->name }}</div>
  5. </td>
  6. <!-- Delete Button -->
  7. <td>
  8. <form action="{{ url('task/'.$task->id) }}" method="POST">
  9. {{ csrf_field() }}
  10. {{ method_field('DELETE') }}
  11. <button type="submit" class="btn btn-danger">
  12. <i class="fa fa-trash"></i> Delete
  13. </button>
  14. </form>
  15. </td>
  16. </tr>

A Note On Method Spoofing

Note that the delete button's form method is listed as POST, even though we are responding to the request using a Route::delete route. HTML forms only allow the GET and POST HTTP verbs, so we need a way to spoof a DELETE request from the form.

We can spoof a DELETE request by outputting the results of the method_field('DELETE') function within our form. This function generates a hidden form input that Laravel recognizes and will use to override the actual HTTP request method. The generated field will look like the following:

  1. <input type="hidden" name="_method" value="DELETE">

Deleting The Task

Finally, let's add logic to our route to actually delete the given task. We can use implicit model binding to automatically retrieve the Task model that corresponds to the {task} route parameter.

In our route callback, we will use the delete method to delete the record. Once the record is deleted, we will redirect the user back to the / URL:

  1. Route::delete('/task/{task}', function (Task $task) {
  2. $task->delete();
  3. return redirect('/');
  4. });