Understanding Laravel — Build a Simple TODO App
By: Inuwa Ibrahim
Tags: Laravel, Website, Web Development, PHP, Programming

Hello. In this tutorial, I will explain the basic concept of Laravel. What it is and how to use it.

We will be building a very simple TODO application, an application that lets you Create, Show, Update, Delete TODO’s . I will explain everything in details.

TODO is basically a list of the tasks that you have to do, or things that you want to do.

WHAT IS LARAVEL?

Laravel is a free, open source framework developed by Taylor Otwell used mostly for web applications.

Before now, building a full web application requires a lot of work.

😫. You had to independently manage and build stuffs such as — Authentication (Login/Registration), Session Management, Database Management etc . With Laravel, you can manage all these without so much stress 😆

REQUIREMENTS

You’ve got to have a basic understanding of PHP (As the framework was built with it).

Check these to get started with Object Oriented Programming with PHP

SETUP LARAVEL

Alright, lets set up Laravel. You’ll need these:

Composer — An application for managing dependencies of PHP and required libraries. Download and Install.

2. Laragon — A portable and fast development environment for PHP. Download and Install

You may need to manually download and Install the latest version of PHP or a version >= 7.2.5. in Laragon

NB — You can also use XAMPP or WAMP.

Installing Laravel (Version 6 was used here)

Open up your Laragon

Click on Start All

Right click on the interface >Click on Quick App > Laravel

> Input the project name — for this project — input - todo

Click OK .

. Sit back as a new Laravel project will be built for you. (Note - This requires Internet connection and may take about 3 minutes).

If everything worked fine —

Your new project will be located in C://laragon/www/todo — For windows users.

To check if it worked -> Visit todo.test on your browser

You should see this

CONGRATULATIOS! Your first Laravel project is up and running. 😃

Now lets build our simple TODO application.

TODO APP

In this app, you will be able to -

Create your own Todo (By inputting a name of your Todo and a description)

(By inputting a name of your and a description) Show a list of Todos you’ve created

you’ve created Edit a Todo — change a value (Either name or description or both)

— change a value (Either name or description or both) Delete a Todo — Remove a Todo from the database

Now open your favorite code editor — PhpStorm, VScode etc. I will recommend PhpStorm — It’s arguably the best for PHP projects. You can use anyone.

SETUP DATABASE

Most applications require a database. We will use this to store records of our Todos .

Open localhost/phpmyadmin/ . Login using root as username and an empty password (Leave it blank) — “ ”

. Login using as username and an empty password (Leave it blank) — Once opened, click on New , input the database name as todos_app and click Create

, input the database name as and click Open your project and navigate to .env file. Set -

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=todos_app

DB_USERNAME=root

DB_PASSWORD=

Okay our database is up and ready, what about the tables?.

You can create tables via the GUI provided by PhpMyAdmin. Yes! but we are not going to do it that way. We will use Laravel’s command tool Interface to do that. WHY? Because it makes managing databases while working as a team way easier and better.

In Laravel, this whole concept of managing databases is known as Migrations .

Read more —

So how do we create our table using migrations:

Head over to your terminal and run the following command —

php artisan make:migration create_todos_table

A migration file will be created in database/migrations directory.

It will look like this — 2020_10_12_create_todos_table.php

Okay, open up the migration file and you’ll see something like this

The Up function — Called whenever you run migrate (used to add new tables, columns, or indexes to your database)

The down function — Called whenever you run rollback (reverse the operations performed by the up method.)

Okay, we have our table with some default columns ( id, timestamps [created_at, updated_at]) auto generated by Laravel. Lets add some other fields/columns to our table — ( name, description ).

To add other column, open the migration file you just created and add the following code. Your file should now look like this.

Alright our database is now looking great. Now check localhost/phpmyadmin, you should see your table and columns..? DID YOU? NOPPE!!

This is because the migration you created is just sitting down there at your Laravel project, you haven’t told Laravel what to do with the migrations.

This is where the command migrate comes into place.

For the migration files you’ve created to have an effect in your database you have to run

php artisan migrate

Do that and check your database, you’ll see the tables and columns you’ve created.

MODEL -> VIEW -> CONTROLLER (MVC)

Model-View-Controller (MVC) is an architectural pattern used by Laravel that separates an application into three main logical components: the model, the view, and the controller.

fig1

Each of these components are built to handle specific development aspects of an application.

Explained

Using fig1.

When a user sends a request to a browser, Laravel checks the routes file to see the url that matches the one entered by the user e.g User visits google.com/home . Laravel check routes folder (Mostly web.php or api.php depending on what you are building)

file to see the that matches the one entered by the user e.g User visits . Laravel check folder (Mostly or depending on what you are building) If the url matches any contained in the routes , Laravel then checks the Controller declared for that route (if there is any) and tells the browser what to do or display.

matches any contained in the , Laravel then checks the declared for that route (if there is any) and tells the browser what to do or display. E.g We visited google.com/home , we want the browser to show the google’s logo and a search field. In our controller, we will declare a method to return a View which contains the logo and search field. All views in Laravel are placed in the resources/views directory

, we want the browser to show the google’s logo and a search field. In our controller, we will declare a method to return a which contains the logo and search field. All views in Laravel are placed in the directory So, we’ve shown the Google logo and the search field. Great! What if we wanted to show dynamic items gotten from the database?. E.g we wanted to show a list of photos uploaded by all users in a website. In this case, we will need to communicate with our database and write some codes in our controller with our database in mind. This is where Model comes into place.

MODEL

In Laravel, Each database table created should have a corresponding model which is used to interact with that table.

For our table — todos , we are going to create a model Todo . This model will be used to interact with our todos table.

Run the following command

php artisan make:model Todo

A model will be created under app/Models directory

Learn more about Eloquent Models here

Read more as there is a naming convention when creating models.

By convention, the “snake case”, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Todo model stores records in the todos table, while an AirTrafficController model would store records in an air_traffic_controllers table.

VIEWS

Okay lets create our views for our Todos app.

For this, we’ll be writing our front end code using HTML and CSS (Bootstrap)

Go to resources/views/layouts (If you cant find layouts, make a new directory called layouts )

(If you cant find layouts, make a new directory called ) Create a new file called app.blade.php — This is where all related common html codes needed across all files will be written to avoid unnecessary boiler plate code.

— This is where all related common html codes needed across all files will be written to avoid unnecessary boiler plate code. Write the following code there

Laravel uses Blade Templating Engine.

Read more

On each html that we are going to be writing that requires these set of codes, we will be extending this app.blade.php .

DISPLAY ALL TODOS VIEW

This will be our first view when you visit the website’s homepage. It basically shows a list of al l todos you’ve created.

Head over to resources/views

Delete the welcome.blade.php . We don't need that anymore

. We don't need that anymore Right click on views -> Create a new PHP file, name it index.blade.php

-> Create a new PHP file, name it Once created write the following code

It should look like this (Don't worry, you cant access it yet on your browser.!)

I populated the todos with dummy data, they will be replaced with the name of the todo you’ll be creating soon.

CREATE TODO VIEW

This view will handle creation of todos — Its basically going to be a form and a submit button.

Head over to resources/views

Right click on views -> Create a new PHP file, name it create.blade.php

-> Create a new PHP file, name it Once created write the following code

You will get something like this. (Again, you cant view this yet on your browser)

TODOS DETAILS VIEW

This view shows the details of a todo when clicked.

Create a new php file under resources/views

Name the file details.blade.php

Write the following code there

It should look like this

EDIT/UPDATE TODO VIEW

A view that lets you make changes to a todo — It is basically same view as creating a todo — but populating the form with already created name and description fields.

Create a new file under resources/views -> Name this one edit.blade.php

-> Name this one Write the following code

You will get something like this

Alright. We are done with all the views required for this app,

VIEWS -> ✔️

CONTROLLERS

Before talking about controllers, head over to routes/web.php

fig a.

Now what is this file? -> It is a file that defines routes that are for your web interface. Does that make any sense? 😶

Okay, see it as place where all the logic behind all the ‘ urls ’ accessed on your website is handled.

For example — On our app — If someone visited todo.test (What should happen?, What view should be displayed?, What logic should be executed?)

All these questions are handled in the routes/web.php file

From fig a above what that code simply means is this ->

When a user makes a get request through the browser by visiting the root directory / (in our case todo.test )

request through the browser by visiting the root directory (in our case ) Execute a function — This function returns a view welcome.blade.php which mostly will reside in the resources/views directory

If you go to your browser and run todo.test -> You should get an error — Because we earlier deleted the welcome.blade.php file.

Now, we want to show a list of todos in our home page.

Edit the routes/web.php file

file In the function declaration block, change welcome to index

to Go to your browser, you should see the dummy todo lists view we created earlier.

Doing it this way is ok. Now imagine you had a complex logic which is to be implemented when a user visits that page, writing a function over and over again can make the routes file messy. This is where controller comes into place.

Controller lets you segment the logic behind a routes file into a single class.

For example, a UserController class might handle all incoming requests related to users, including showing, creating, updating, and deleting users.

CREATE A CONTROLLER

This controller handles the logic behind our todos application

Run the command

php artisan make:controller TodoController

A controller will be created under app/Http/Controllers

Now open the routes/web.php file

file Change the code to this

Route::get('/', [TodoController::class, 'index']);

The term ‘index’ is a method which we will create in the TodoController class which will help us display the list of todos

WRITING LOGIC

Open TodoController you just created

you just created Write a function that will handle showing a list of all todos you’ve created

public function index(){ return view('index'); }

Head to your browser and load todo.test

You should still see a list of dummy todos created

Awesome, now our code looks cleaner

Doing the same thing for our other views, our final code looks like this

routes/web.php

Route::get('/', [TodoController::class, 'index']);



Route::get('create', [TodoController::class, 'create']);



Route::get('details', [TodoController::class, 'details']); Route::get('edit', [TodoController::class, 'edit']); Route::post('update', [TodoController::class, 'update']);



Route::get('delete', [TodoController::class, 'delete']);

TodoController.php

public function index(){



return view('index');



} public function create(){

return view('todos.create');

} public function details(){



return view('details');



}



public function edit(){



return view('edit');



} public function update(){



//we will write codes for updating a todo here



} public function delete(){



//we will write codes for deleting a todo here



}

Head over to your browser, all views should display correctly.

Good…But we aren’t communicating with our database yet, all items were manually generated by us in our html

INTERACTING WITH OUR MODEL

As stated earlier the model is used to interact with a database table. We already have our table ( todos ) and model ( Todo ) created. Our model has to interact with the methods in our controller for performing basic CRUD operations.

DISPLAYING LIST OF TODO’S

Right now, we have not created any todo, so our database records is practically empty. If you take a look at our home page todo.test , It shows a list of dummy data which we manually added in our index.blade.php file. We will now change that and get the data from our todos table

Open TodoController.php

Go to index() function

function In the declaration block, add these code

public function index(){



$todo = Todo::all();

return view('index')->with('todos', $todo);



}

What this code does is -> Get all the data in the todos table. (Remember we are interacting with our table via our model — Todo ) -> Pass these to our view ( index.blade.php )

Open index.blade.php

Change the code there to these

Now open your browser and load todo.test. The page will be empty. This is expected as we haven’t created any todo yet.

CREATING TODO

Now lets create some todos

Head over to create.blade.php

Add an action to the form tag and a csfr (For handling Cross-site request forgery attack).

Should now look like this —

Add a route for store-data and a method in our TodoController for handling creation of todos — call it store

Route::post('store-data', [TodoController::class, 'store']);

Notice how this is a post request because we are sending data to the server

Open TodoController and add the method store()

Here is what we did -> Validate the data by marking the fields as required, Get all the request/data coming in -> Store the data in an object -> Save them in a database -> Display a success message -> Return to Homepage

Now to show the success message you have to edit app.blade.php file and add these line inside the container div

@if(session()->has('success'))

<div class="alert alert-success">



{{ session()->get('success') }}



</div>

@endif

Go ahead and create a Todo , It should work as expected.

DISPLAY TODO DETAILS

Here, we should display the details of a particular todo when clicked.

How do we do that? Simple -> Get the id of the todo you want to view -> Using that id , get the record for that particular todo (name, description)

Go to index.blade.php

Change the url reference for viewing details to something like this

Open routes/web.php

Change details route to this

Route::get('details/{todo}', [TodoController::class, 'details']);

Open TodoController , change the method to this

public function details(Todo $todo){



return view('details')->with('todos', $todo);



}

Open details.blade.php and change it to this

Test on your browser, you should be able to view the details of each todo that you’ve created.

UPDATING A TODO

So, you’ve created a todo , good! what if you made a mistake and wanted to change maybe the name or description — you could do that via phpMyAdmin but SERIOUSLY? We need to be able to change that on our website.

Open routes/web.php

Change the route for editing a todo to this

Route::get('edit/{todo}', [TodoController::class, 'edit']);

Go to your edit.blade.php and change it to this

Change the route for ‘ update ’ to this

Route::post('update/{todo}', [TodoController::class, 'update']);

Now open TodoController , add these to the update() method.

Try to edit a todo and it should work

DELETE A TODO

Now we need to delete a todo from the database table

Open routes/web.php

Change the delete route to this

Route::get('delete/{todo}', [TodoController::class, 'delete']);

Open details.blade.php , change the delete url to this:

<a href="/delete/{{$todos->id}}"><span class="btn btn-danger">Delete</span></a>

Open TodoController and add this to the delete() method

Delete a todo and it should work.

FINALLY! We’ve come to the end — the end of this never ending war, now go outside and receive some vitamin D.

I hope you’ve learnt how to use Laravel to perform basic CRUD operations which is basically the building blocks of all websites.!

Thanks!