Build a Task Manager Application with Laravel

Building a Laravel CRUD Application


In this tutorial, we’ll be building a Laravel CRUD Application with Laravel 6 along with authentication and we’d get to do the following.

  • Learn how to set up a Laravel Application from scratch
  • Learn  to create a Database in PHPMyAdmin
  • Work with laravel blade templates
  • Work with Models, Migrations, and Controllers in Laravel
  • Work with Databases in Laravel
  • Learn How to perform CRUD (Create Read Update Delete) operations in Laravel.

A good way to solidify your knowledge in any programming language or framework is to actually build something with it whether small scale or large, build something! For the purpose of this tutorial, we will be creating a simple task manager application using Laravel.

This tutorial assumes that you have VSCode, PHP and composer installed on your computer. If you do not, then follow this link to install XAMPP, a PHP and MySQL server on your computer. Once you have Xampp installed, follow this link to set up Composer on your computer. I also assume that you have at least a basic knowledge of Laravel and how it works.

Setting Up Our Application

once Xampp and Composer have been set up and configured fully, Let’s get started with our application.

Open up a terminal and navigate to your preferred folder eg /desktop and run

composer create-project laravel/laravel lara-tasks 

I used lara-tasks as the name of my project and I’d assume you did the same. You should hit the enter key to run the command above. this command downloads a copy of a starter Laravel application in a folder called lara-tasks on your desktop folder. If you’re running the command for the first time, it might take a while to complete depending on your internet download speed.

Next, open up the XAMPP application and start your Apache and MySQL server as shown below:

Your XAPP screen should look like this.

Once Apache and MySQL are running, open up your favorite browser (eg Chrome) and type in localhost/phpmyadmin to open up PHPMyAdmin. PHPMyAdmin is going to be used to create the database used for our application.

Once PHPMyAdmin boots up, click on the ‘new’ button on the left sidebar to create a new database.

PHPMyAdmin homepage

On the page that loads, type in your preferred database name and click on the create button.

Create a database in PHPMyAdmin

Once that is done, head over to your terminal and cd (change directory) into the lara-tasks folder after Laravel has been installed I.e when you get a screen similar to this:

run cd lara-tasks && code . to move into the folder and open up the project folder in VSCode Next, open up the .env file in VSCode and modify the database credentials and the APP_NAME as such

APP_NAME=Lara-Tasks
APP_ENV=local
APP_KEY=base64:Xn6T52/rkSMIclgPNPQ3AiugSpWhjNpvDwlFaDEmZ/M=
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=lara-tasks
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

 

Creating The Tasks Migration

Once that is done, it’s time to start with the functionalities of our application.

We need to set up a model and migration to store our Tasks.

open up a new terminal window in your project folder and run:

 php artisan make:migration create_tasks_table --create=tasks

This creates a file similar to XXXX-XXXcreate_tasks_table.php in your Database/migrations folder.

Open the file and modify the code to look similar to this:

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
  
class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}

The public function up() block of code is a command that tells Laravel to create the tasks table with fields inside the database when the migration is run.

The public function down () block as you can guess, tells Laravel to delete the table that was created whenever the migration is rolled back.

Once that is done, run thephp artisan migrate command to implement our changes in the database.

If you open up the database in PHPMyAdmin, you’ll notice that our database now has some content.

Making and Setting Up the TaskController

Next, we’re going to create a controller to handle CRUD operations in our Tasks Manager Application.

run php artisan make:controller TaskController --resource --model=Task

Once this is done, we need to update our Routes/web.php file by adding the following code to it.

 Route::resource('tasks','TaskController');

After running the make:controller command above, you will find a new file in the app/Http/Controllers/TaskController.php with 7 methods by default: namely

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

Update the file to become similar to the code below:

namespace AppHttpControllers;
  
use AppTask;
use IlluminateHttpRequest;
  
class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        $tasks = Task::latest()->paginate(5);
  
        return view('tasks.index',compact('tasks'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }
   
    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        return view('tasks.create');
    }
  
    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
  
        Task::create($request->all());
   
        return redirect()->route('tasks.index')
                        ->with('success','Task created successfully.');
    }
   
    /**
     * Display the specified resource.
     *
     * @param  AppTask  $task
     * @return IlluminateHttpResponse
     */
    public function show(Task $task)
    {
        return view('tasks.show',compact('task'));
    }
   
    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppTask  $task
     * @return IlluminateHttpResponse
     */
    public function edit(Task $task)
    {
        return view('tasks.edit',compact('task'));
    }
  
    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppTask  $task
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, Task $task)
    {
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
  
        $task->update($request->all());
  
        return redirect()->route('tasks.index')
                        ->with('success','Task updated successfully');
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  AppTask  $task
     * @return IlluminateHttpResponse
     */
    public function destroy(Task $task)
    {
        $task->delete();
  
        return redirect()->route('tasks.index')
                        ->with('success','Task deleted successfully');
    }
}

Next, Open up the App/Task.php file and update it as such:

<?php
  
namespace App;
  
use IlluminateDatabaseEloquentModel;
   
class Task extends Model
{
    protected $fillable = [
        'name', 'detail'
    ];
}

Creating Our Blade Views

Now that our application structure is done, let’s bring our application to live by displaying it visually. to do this, we make use of Laravel’s blade templating system.

To begin, in the resources/views directory, create the following files.

  • layout.blade.php
  • index.blade.php
  • create.blade.php
  • edit.blade.php
  • show.blade.php

Open up the layout.blade.php and put the code below in it.

<html>
<head>
    <title>Lara Tasks</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<div class="container">
    @yield('content')
</div>

</body>
</html>

Next, open up the index.blade.php file and add the following code to it.

@extends('tasks.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 6 Tasks Manager Codesource.io</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{%20route('tasks.create')%20}}"> Create New task</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
   
    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Details</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($tasks as $task)
        <tr>
            <td>{{ ++$i }}</td>
            <td>{{ $task->name }}</td>
            <td>{{ $task->detail }}</td>
            <td>
                <form action="{{ route('tasks.destroy',$task->id) }}" method="POST">
   
                    <a class="btn btn-info" href="{{%20route('tasks.show',$task->id)%20}}">Show</a>
    
                    <a class="btn btn-primary" href="{{%20route('tasks.edit',$task->id)%20}}">Edit</a>
   
                    @csrf
                    @method('DELETE')
      
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
    </table>
  
    {!! $tasks->links() !!}
      
@endsection

Next, open the create.blade.php file and add the code below to it:

@extends('tasks.layout')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New task</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{%20route('tasks.index')%20}}"> Back</a>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('tasks.store') }}" method="POST">
    @csrf
  
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                <input type="text" name="name" class="form-control" placeholder="Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Detail:</strong>
                <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
   
</form>
@endsection

Once, we have saved our create.blade.php view, we need to allow users to edit tasks. To do that, open up the edit.blade.php file and type in the following code:

@extends('tasks.layout')
   
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit task</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{%20route('tasks.index')%20}}"> Back</a>
            </div>
        </div>
    </div>
   
    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
  
    <form action="{{ route('tasks.update',$task->id) }}" method="POST">
        @csrf
        @method('PUT')
   
         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Name:</strong>
                    <input type="text" name="name" value="{{ $task->name }}" class="form-control" placeholder="Name">
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Detail:</strong>
                    <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail">{{ $task->detail }}</textarea>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
              <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
   
    </form>
@endsection

Next, we would want to be able to open up individual tasks on a separate page.

To enable this functionality, open up your show.blade.php file and put in the following code:

@extends('tasks.layout')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show task</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{%20route('tasks.index')%20}}"> Back</a>
            </div>
        </div>
    </div>
   
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $task->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $task->detail }}
            </div>
        </div>
    </div>
@endsection

Wrapping Up: Previewing Our Laravel crud app

Once that is done run the php artisan serve command in your terminal, then head over to localhost:8000/tasks in your browser to see something similar to this after you have created your first task: 

Tasks Manager Application with Laravel

 You can find the full source code of the Laravel crud application on the github link


Share on social media

//