Laravel 8 Tutorial for Beginner: Create your First To-Do App

Published on : March 10,2023
Laravel 8 Tutorial for Beginner: Create your First To-Do App

In this tutorial, we'll go through the process of creating a simple To-Do app in Laravel 8. This tutorial is designed for beginners who are new to Laravel and want to learn how to create a basic CRUD (Create, Read, Update, Delete) application.

 

Prerequisites

Before we begin, you'll need to have the following installed:

  • PHP 7.3 or later
  • Composer
  • Laravel 8
  • A text editor (e.g. Visual Studio Code, Sublime Text, etc.)

 

Step 1: Install Laravel

First, we need to install Laravel. Open your terminal and run the following command:

composer create-project --prefer-dist laravel/laravel todoapp

This will create a new Laravel project named "todoapp" in a folder called "todoapp" in your current directory.

 

Step 2: Set Up Database

Next, we need to set up our database. Open the .env file in your project root and set the following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=todoapp
DB_USERNAME=root
DB_PASSWORD=

Replace the DB_DATABASE, DB_USERNAME, and DB_PASSWORD with your own values.

Next, create a new database called "todoapp" in your MySQL server.

 

Step 3: Create Task Model and Migration

Now, let's create a Task model and migration. In your terminal, run the following command:

php artisan make:model Task --migration

This will create a new Task model and migration file in your app and database/migrations directories, respectively.

Open the database/migrations/<timestamp>_create_tasks_table.php file and update the up method to look like this:

public function up()
{
   Schema::create('tasks', function (Blueprint $table) {
       $table->id();
       $table->string('title');
       $table->boolean('completed')->default(false);
       $table->timestamps();
   });
}

This will create a tasks table in your database with an id, title, completed, and timestamps columns.

Run the migration using the following command:

php artisan migrate

 

Step 4: Create Task Controller

Next, let's create a TaskController to handle the logic for our tasks. In your terminal, run the following command:

php artisan make:controller TaskController --resource

This will create a new TaskController in your app/Http/Controllers directory with CRUD methods pre-defined.

 

Step 5: Create Task Routes

Now, let's define our routes for our tasks. Open the routes/web.php file and add the following:

use App\Http\Controllers\TaskController;

Route::get('/', [TaskController::class, 'index'])->name('tasks.index');
Route::get('/tasks/create', [TaskController::class, 'create'])->name('tasks.create');
Route::post('/tasks', [TaskController::class, 'store'])->name('tasks.store');
Route::get('/tasks/{task}', [TaskController::class, 'show'])->name('tasks.show');
Route::get('/tasks/{task}/edit', [TaskController::class, 'edit'])->name('tasks.edit');
Route::put('/tasks/{task}', [TaskController::class, 'update'])->name('tasks.update');
Route::delete('/tasks/{task}', [TaskController::class, 'destroy'])->name('tasks.destroy');

These routes will define the URLs for our CRUD operations.

 

Step 6: Create Task Views

Next, we need to create our views for our tasks. Create a new folder called tasks in your resources/views directory.

Index View

Create a new file called index.blade.php in the tasks folder. Add the following code to display a list of tasks:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1>Tasks</h1>
                    <a href="{{ route('tasks.create') }}" class="btn btn-primary">Create Task</a>
                </div>

                @if (session('success'))
                    <div class="alert alert-success">{{ session('success') }}</div>
                @endif

                <table class="table">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($tasks as $task)
                            <tr>
                                <td>{{ $task->title }}</td>
                                <td>{{ $task->completed ? 'Completed' : 'Pending' }}</td>
                                <td>
                                    <a href="{{ route('tasks.show', $task) }}" class="btn btn-info btn-sm">View</a>
                                    <a href="{{ route('tasks.edit', $task) }}" class="btn btn-warning btn-sm">Edit</a>
                                    <form action="{{ route('tasks.destroy', $task) }}" method="POST" class="d-inline-block">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                    </form>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </div>
@endsection

 

Create View

Create a new file called create.blade.php in the tasks folder. Add the following code to display a form to create a new task:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1>Create Task</h1>
                    <a href="{{ route('tasks.index') }}" class="btn btn-secondary">Back</a>
                </div>

                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form action="{{ route('tasks.store') }}" method="POST">
                    @csrf
                    <div class="form-group">
                        <label for="title">Title</label>
                        <input type="text" name="title" id="title" class="form-control">
                    </div>
                    <button type="submit" class="btn btn-primary">Create</button>
                </form>
            </div>
        </div>
    </div>
@endsection

 

Show View

Create a new file called show.blade.php in the tasks folder. Add the following code to display a single task:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
           <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1>{{ $task->title }}</h1>
                <div>
                    <a href="{{ route('tasks.edit', $task) }}" class="btn btn-warning">Edit</a>
                    <form action="{{ route('tasks.destroy', $task) }}" method="POST" class="d-inline-block">
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="btn btn-danger">Delete</button>
                    </form>
                </div>
            </div>

            <table class="table">
                <tbody>
                    <tr>
                        <th>Title</th>
                        <td>{{ $task->title }}</td>
                    </tr>
                    <tr>
                        <th>Status</th>
                        <td>{{ $task->completed ? 'Completed' : 'Pending' }}</td>
                    </tr>
                    <tr>
                        <th>Created at</th>
                        <td>{{ $task->created_at->format('d M Y H:i') }}</td>
                    </tr>
                    <tr>
                        <th>Updated at</th>
                        <td>{{ $task->updated_at->format('d M Y H:i') }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
@endsection

 

Edit View

Create a new file called edit.blade.php in the tasks folder. Add the following code to display a form to edit a task:

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1>Edit Task</h1>
                    <a href="{{ route('tasks.index') }}" class="btn btn-secondary">Back</a>
                </div>

                @if ($errors->any())
                    <div class="alert alert-danger">
                        <ul>
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form action="{{ route('tasks.update', $task) }}" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="form-group">
                        <label for="title">Title</label>
                        <input type="text" name="title" id="title" class="form-control" value="{{ $task->title }}">
                    </div>
                    <div class="form-group">
                        <label for="completed">Completed</label>
                        <select name="completed" id="completed" class="form-control">
                            <option value="0" {{ $task->completed ? '' : 'selected' }}>Pending</option>
                            <option value="1" {{ $task->completed ? 'selected' : '' }}>Completed</option>
                        </select>
                    </div>
                    <button type="submit" class="btn btn-primary">Update</button>
                </form>
            </div>
        </div>
    </div>
@endsection

 

Step 7: Test the Application

Finally, let's test our application. Run the following command to start the development server:

php artisan serve

Now, you can access the application at http://localhost:8000/tasks.

You should be able to perform the following actions:

  • View a list of tasks
  • Create a new task
  • View a single

Categories : Laravel

Tags : PHP Laravel 8 CRUD operations To-Do App Beginners

Abhay Dudhatra
Abhay Dudhatra
I am a full-stack developer who is passionate about creating innovative solutions that solve real-world problems. With expertise in technologies such as PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap, I love to share my knowledge and help others in the industry through writing tutorials and providing tips. Consistency and hard work are my mantras, and I constantly strive to improve my skills and stay up-to-date with the latest advancements in the field. As the owner of Open Code Solution, I am committed to providing high-quality services to my clients and helping them achieve their business objectives.


161 Comments

fenofibrate 200mg pills fenofibrate ca fenofibrate price


buy cialis 40mg online cheap buy viagra online sildenafil citrate


minoxidil buy online purchase tamsulosin online cheap best place to buy ed pills online


order acarbose 25mg without prescription fulvicin pill order generic griseofulvin 250mg


buy aspirin medication order levofloxacin generic order zovirax online


florinef 100 mcg cheap brand fludrocortisone buy imodium 2 mg without prescription


purchase monograph pills buy colospa 135mg sale generic cilostazol 100mg


brand prasugrel 10 mg prasugrel 10 mg sale detrol 2mg usa


ferrous sulfate pill ferrous pills purchase sotalol generic


cheap pyridostigmine buy generic feldene for sale buy rizatriptan 10mg generic


latanoprost us xeloda cost order exelon 6mg pills


order premarin online cheap sildenafil pill buy sildenafil online cheap


prilosec cost order generic montelukast 5mg buy generic lopressor 100mg


buy generic micardis over the counter hydroxychloroquine for sale online buy molnunat cheap


cheap generic cialis buy cialis 10mg online viagra 50mg sale


buy cenforce 50mg for sale order aralen 250mg sale aralen 250mg cheap


buy modafinil pills phenergan online buy deltasone 10mg drug


cefdinir 300mg for sale omnicef brand buy prevacid pill


buy isotretinoin 20mg generic amoxil 500mg drug buy zithromax 250mg pill


buy azithromycin 250mg sale generic azipro gabapentin 100mg generic


purchase atorvastatin online cheap atorvastatin 10mg cost norvasc generic


sugarhouse casino online furosemide brand cheap furosemide 100mg


order pantoprazole 40mg for sale order lisinopril 10mg purchase phenazopyridine pill


slot casino order doxycycline for sale buy albuterol cheap


online slot machines stromectol 6mg ca stromectol pharmacy


purchase amantadine online buy atenolol generic dapsone 100 mg brand


best online casinos buy generic levothroid order synthroid 100mcg pill


buy clomiphene 100mg pills clomid 100mg sale azathioprine cheap


buy methylprednisolone 16mg online brand aristocort triamcinolone 10mg generic


order levitra 10mg sale brand levitra buy tizanidine pills for sale


purchase coversum generic order aceon 8mg online buy allegra 180mg pill


dilantin 100mg usa cyclobenzaprine 15mg cost order oxybutynin 2.5mg


buy ozobax medication toradol oral ketorolac oral


order loratadine pill where to buy claritin without a prescription priligy buy online


buy lioresal pills for sale ozobax drug buy ketorolac online cheap


buy fosamax 35mg pills buy fosamax medication nitrofurantoin 100 mg tablet


inderal pills buy motrin generic buy generic clopidogrel


cost pamelor buy paracetamol 500 mg sale buy paracetamol 500 mg generic


buy amaryl pills order misoprostol 200mcg pills etoricoxib 60mg generic


warfarin 2mg cost purchase medex online order reglan 10mg


purchase pepcid order losartan 25mg pill buy tacrolimus 5mg generic


buy astelin 10 ml sprayer zovirax 800mg pills buy avalide pills


order esomeprazole pills buy topiramate 200mg sale buy generic topamax


sumatriptan where to buy dutasteride sale order dutasteride online


order allopurinol 300mg generic purchase allopurinol online cheap rosuvastatin 20mg ca


ranitidine 300mg pill meloxicam 7.5mg cheap buy celecoxib 100mg sale


buy buspar sale buy cordarone 100mg pill buy cheap amiodarone


order flomax 0.2mg pills simvastatin 20mg pills purchase zocor pill


aldactone 100mg cost aldactone 25mg ca buy finasteride without a prescription


pay for assignment cheap term papers cheap paper writing services


fluconazole 100mg oral order ciprofloxacin 500mg online cheap cheap baycip


buy aurogra 50mg generic buy aurogra sale buy estrace sale


flagyl 200mg pills order metronidazole 400mg for sale keflex online buy


lamictal pills buy generic mebendazole purchase mebendazole pills


generic cleocin 300mg order cleocin 150mg generic best place to buy ed pills online


tretinoin usa avanafil drug buy generic avanafil over the counter


nolvadex 20mg canada nolvadex 20mg generic generic symbicort


tadacip 10mg ca tadalafil 10mg generic order indocin 50mg generic


buy generic axetil buy cefuroxime 250mg online methocarbamol oral


desyrel 50mg oral sildenafil 100mg generic purchase clindac a generic


terbinafine for sale online lamisil 250mg uk blackjack online real money


order aspirin how to start an online gambling business best online casino real money


essay buy online order cefixime 100mg online cheap suprax price


order essays online online casino real money no deposit pala casino online


order trimox generic buy biaxin 500mg for sale clarithromycin 500mg pills


order calcitriol without prescription buy generic calcitriol order tricor 160mg generic


clonidine 0.1 mg brand spiriva 9mcg cost order tiotropium bromide 9mcg online cheap


best pimple medication for teenagers adult female acne buy oxcarbazepine 300mg generic


purchase minocin generic cost ropinirole ropinirole over the counter


purchase uroxatral pills heartburn after taking antibiotics wha tmedicine should i take for heartburn


buy sleeping pills online canada online doctors who prescribe zolpidem online semaglutide weight loss programs


buy generic letrozole buy letrozole for sale buy aripiprazole 30mg generic


quit smoking medication list best pain killers for arthritis list of most powerful painkillers


medroxyprogesterone over the counter order provera 10mg generic buy generic hydrochlorothiazide 25 mg


antiviral herpes medication cost daily pills for herpes best meds for pre diabetics


cyproheptadine 4mg cheap order nizoral 200mg nizoral 200 mg generic


supplements that kill fungus antiviral medication herpes simplex 1 what to drink to lower blood pressure quickly


buy generic cymbalta over the counter buy generic cymbalta provigil online order


medications for duodenal ulcer liquid prescription ulcer medication list of urinary antiseptic drugs


buy promethazine 25mg generic stromectol 3mg brand stromectol medication


same day birth control prescription best antibiotics for bacterial prostatitis home remedies to increase ejaculation


cheap deltasone 5mg buy generic amoxil 1000mg cheap amoxil sale


best supplement for heartburn anti gas bloating pills pills to curerunny farts


buy azithromycin 500mg pill buy zithromax 500mg online order generic gabapentin 100mg


buy urso no prescription order urso buy zyrtec


brand atomoxetine order quetiapine 50mg buy sertraline no prescription


buy lasix 100mg pills order generic doxycycline 200mg buy albuterol pills


lexapro 20mg oral naltrexone pills naltrexone drug


combivent 100 mcg drug buy generic decadron over the counter zyvox generic


augmentin price cost augmentin 625mg clomiphene 50mg pills


vardenafil 20mg cheap cheap vardenafil plaquenil order


tegretol usa buy lincomycin generic lincocin 500mg tablet


order cenforce online buy aralen 250mg glycomet for sale online


purchase duricef without prescription purchase epivir pills how to get combivir without a prescription


atorvastatin 10mg brand amlodipine 5mg drug buy generic lisinopril online


cabergoline 0.25mg canada buy priligy online cheap order dapoxetine 90mg sale


order depo-medrol without prescription buy triamcinolone 10mg where can i buy clarinex


cytotec canada buy misoprostol cheap buy diltiazem pills


buy piracetam generic cheap nootropil anafranil 50mg uk


buy zovirax paypal allopurinol online order order rosuvastatin 20mg online cheap


order itraconazole 100mg online cheap buy sporanox 100 mg sale tindamax 300mg oral


ezetimibe 10mg without prescription order tetracycline 250mg generic tetracycline 500mg uk


zyprexa 10mg tablet valsartan pills buy diovan online cheap


flexeril over the counter lioresal uk ketorolac for sale


colchicine 0.5mg oral buy methotrexate 2.5mg generic methotrexate 2.5mg uk


buy acne pills online accutane 40mg pills permanent acne removal treatment


prescription allergy medicine list zyrtec ca top rated pill for itching


medicine to make you puke baycip oral



cost deltasone 5mg order prednisone pill


best treatment for abdominal pain purchase baycip online cheap


acne medication pills that work oral tretinoin gel strong acne medication from dermatologist


alternative painkiller to co codamol purchase zyloprim online


isotretinoin pill isotretinoin 40mg usa accutane over the counter


sleep meds prescribed online phenergan 10mg pills


Мама уезжает, и я хотел сделать ей приятное перед отъездом. Заказал на "Цветов.ру" букет ярких тюльпанов. Честно, мама даже не ожидала, что это вне Дня Матери! Спасибо за оперативность и качество! Советую! Вот ссылка https://coredrillchina.ru/saratov/ - заказ цветов с доставкой


order amoxicillin 1000mg generic buy amoxil 250mg generic amoxicillin 500mg for sale


azithromycin medication buy azithromycin 500mg generic buy zithromax 500mg pills


cheap gabapentin generic order neurontin 100mg generic


buy azithromycin 500mg sale buy azithromycin sale azipro 250mg price


purchase lasix online furosemide price


buy omnacortil 5mg without prescription purchase prednisolone pill buy generic omnacortil over the counter


prednisone 20mg sale prednisone 5mg price


order amoxicillin 1000mg for sale amoxicillin 1000mg brand amoxicillin 500mg for sale


doxycycline 100mg canada monodox without prescription


ventolin 2mg canada order albuterol inhalator without prescription purchase albuterol generic


augmentin pill buy cheap augmentin


purchase levoxyl online cheap buy levothroid online cheap where to buy synthroid without a prescription


buy generic levitra online vardenafil 10mg drug


purchase serophene online cheap cost clomiphene purchase clomiphene pill


rybelsus price buy rybelsus 14mg generic rybelsus 14 mg uk


rybelsus 14mg us semaglutide medication semaglutide for sale online


buy prednisone buy deltasone 20mg pills prednisone 20mg ca


С того дня, как я начал правильно питаться, моя жизнь изменилась. Я благодарю компанию 'все соки' за их https://h-100.ru/collection/sokovyzhimalki-dlya-granata - соковыжималку для граната. Теперь каждое утро начинается с бодрящего гранатового сока!


isotretinoin 20mg without prescription isotretinoin ca buy accutane pills for sale


ventolin 2mg sale purchase ventolin online ventolin inhalator over the counter


order amoxil without prescription buy amoxil sale amoxicillin online


buy augmentin 375mg generic buy augmentin 375mg sale clavulanate brand


azithromycin price generic azithromycin zithromax 250mg brand


buy levothyroxine tablets order synthroid 75mcg generic synthroid 75mcg over the counter


levitra 20mg cost order vardenafil 20mg online cheap purchase levitra generic


online casino for real money poker online play slots games


buy hydroxychloroquine 400mg order plaquenil 400mg online buy hydroxychloroquine


buy pregabalin pills purchase lyrica generic order pregabalin without prescription


buy tadalafil 10mg pill order cialis 20mg sale buy tadalafil 5mg without prescription


cheap triamcinolone buy triamcinolone 4mg online cheap buy aristocort online


cenforce canada cenforce usa buy cenforce 100mg for sale


buy desloratadine clarinex 5mg price brand clarinex


chloroquine ca where to buy aralen without a prescription aralen tablet


loratadine pills loratadine 10mg generic purchase claritin generic


order orlistat 120mg without prescription order generic orlistat 120mg purchase diltiazem online


buy lipitor online cheap atorvastatin pill atorvastatin 20mg us


buy amlodipine online amlodipine over the counter buy amlodipine tablets


buy zovirax online how to buy allopurinol allopurinol 100mg generic


zestril 5mg cost order zestril 5mg for sale zestril 2.5mg cheap


buy crestor 10mg pill order crestor pills buy generic ezetimibe


order prilosec pills prilosec canada order omeprazole pills


motilium online buy cheap domperidone buy tetracycline 250mg online cheap


metoprolol canada metoprolol 100mg ca buy metoprolol cheap


order cyclobenzaprine 15mg generic order baclofen sale oral baclofen 10mg


buy tenormin 50mg for sale tenormin 50mg price atenolol canada


Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles