Home » Laravel14 November 2016

Laravel: Simple CRUD (Add, Edit, Delete, View) [Beginner Tutorial]

This beginner tutorial/article shows how you can create a simple/basic CRUD (Create, Read, Update, Delete) system or application using Laravel. Laravel is a popular open-source PHP MVC Framework with lots of advanced development features.

Installing Laravel has been explained here.

Laravel Application Folder Structure

After you have successfully installed Laravel, you need to know about the application structure (folder structure) of Laravel. The root directory of Laravel contains the following directories. Sub-directories of app directory is also listed below.

Artisan Command Line Tool

The other important thing to understand is the Artisan command line tool. Laravel consists of a command line interface named ‘Artisan’. It is based upon the Symfony Console Component.

Artisan contains a lot of helpful commands for application development. To view the list of all Artisan commands, you need to go to your Laravel root folder and run the following command:

You will see the following list of available commands after running the above command:

As you can see above, there are many commands that do different helpful jobs. You can clear Cache with a single command. You can run scheduled tasks, create different controller, events, etc. classes, and so on.

As an example, to clear your Laravel application cache, you can simply run the following command:

We will be using artisan commands later in this tutorial.

Create Database

After we have some understading of Laravel application/folder structure and about Artisan CLI, we can now move forward to create our basic CRUD (Create, Read, Update, Delete) application in Laravel.

First of all, we need to create a new database and a table inside the newly created database. We will name our database as test and create a table named news inside the database test.

Here’s the MySQL query to create database:

Database Configuration Settings

After you create your database, you need to enter your database name and database login credentials in Laravel’s configuration settings file. Laravel’s database configuration file is present at /path-to-laravel-root/config/database.php.

In this file, you will find connection defined for different databases like sqlite, mysql, and pgsql. We will be using MySQL database. Therefore, we will update the information for mysql database only.

The database name of our application in this tutorial is test. The database username in my system is root and password is also root. Database host for my local machine is localhost and port is 3306. Here is the update done by my side. You have to update it according to your database settings.

To use database commands from Artisan Command Line Tool, you also need to update database settings in /path-to-laravel-root/.env file because Artisan fetches database settings from .env file. Here’s the updated .env file on my computer:

Creating Table

You can create or modify tables simply through SQL queries or from GUI like phpMyAdmin. But, Laravel provides you another option to do so. It’s called Migrations. With Laravel Migrations, you can create/modify database tables from PHP code.

We will be creating a table named news. Here are the steps to do so:

– Open terminal/command-prompt
– Go to your laravel root directory.
– In my case (Ubuntu 16.04) it will be:

– Run the following command:

This will create migrations table in your test database.

– Now, run the following command:

This will create a new class named CreateNewsTable at your-laravel-root/database/migrations/2016_08_26_114034_create_news_table.php. create_news_table name is preceded by date value.

CreateNewsTable class will have two empty functions up() and down(). Table creation code should be added in up() function and table deletion code should be added in down() function.

Here is the updated CreateNewsTable class:

Note: Running the following command will add basic schema code to up() and down() function of migration class

Run the following command to execute the migration class

The table news has been created.

Adding Test Data to Database Table

This is optional. If you wish to add sample/test data to your database table then you can do this with the Laravel’s seed classes. This method is also called Database Seeding.

In this example, we will be adding some test data to your news table.

– Run the following command on terminal/command-prompt:

This will create a new class named NewsTableSeeder at your-laravel-root/database/seeds/NewsTableSeeder.php.

NewsTableSeeder class will have an empty function run(). Data insertion code should be added in the run() function.

Here is the updated NewsTableSeeder class:

Run the following command to execute run() function of NewsTableSeeder class. This will add data to news table.

Using Faker PHP Library to generate fake data

We can also use Faker Library to generate fake data for our database table. Here is the NewsTableSeeder class using Faker library:

Creating Model

Model classes are used for database operations like querying database tables or inserting/updating records in the database table. Laravel uses the Eloquent ORM (Object Relational Mapper) for implementing database tasks. In this, each database table is associated with a Model class.

Run the following command to create the Model class for table news:

The News model class will be created at your-laravel-root-folder/app/News.php.

You need to add the table name, primary key of the table, etc. in the News class.

Here’s the updated News class:

Routing

Before moving on to Controller, we first look into routes file. The route file is present at app/Http/routes.php. Generally, the use of route file is to connect request URL to Controller methods.

Here is a basic route example:

You will get ‘Hello World’ printed when you browse http://your-laravel-site/foo

In the above route, we wrote some static code. We will now write a new route that will link to a function/action of our NewsController class.

This will route to index() function of News controller class when we browse http://your-laravel-site/news

For our application, we need to put the following code in our application’s app/Http/routes.php file.

Creating Controller

In Controller class, we write all the logics to fetch data from database table, process it and pass it to views. Controller clasess are saved in app/Http/Controllers directory.

Run the following code to create a NewsController controller class.

This will create NewsController class at app/Http/Controller/NewsController.php. Using --resource will create basic CRUD routes in the News controller class. It will create empty functions named index, create, update, destroy, etc.

In controller functions we call our model class, fetch the data, process it, and pass the data to view file.

In the index() function below, News data is first fetched and then the view template is returned with using view() method.
In store() function, form submit request is fetched, then the input data is saved into database using create() method and then redirected to news.index page.

Here is the updated NewsController class used for this tutorial’s application:

Views

Views are html files present in laravel-root/resources/views directory. Laravel uses Blade templating engine in views which helps to use loops and if/else conditions like PHP in the view html file.

Laravel uses blade templating engine, so the views files should be named as viewname.blade.php.

As you can see above, in index() function of NewsController class, we have passed news data into news.index view. This means that the view should be stored in laravel-root/resources/views/news/index.blade.php.

For this tutorial, we will first create a master template where we include/define the title, header, content and footer. We then extend the master template for other pages of our application. We also display success and error flash message on master template.

Here is our master template (laravel-root/resources/views/layout/master.blade.php):

resources/views/news/index.blade.php will be extending master.blade.php template and then displaying news item in content section. The news data for index template comes from index() function of NewsController class.

In the index template, you will also see a Delete form. The delete action goes to destroy($id) function of NewsController class. Instead of link, button is to be used for Delete purpose in Laravel.

$news->links() shows pagination links.

The news index page will look like below:

news index

Now, we move towards creating an add news form. We can simply write the html syntax to create the form. But, Laravel also provides us an option to create form using Illuminate/Html package.

To install this package, update your-laravel-root/composer.json file. Add this:

Then run composer update command on terminal:

This will install the laravelcollective/html package to your laravel application.

After that, edit laravel-root/config/app.php.

Now, create template file to add news. The add news form post action goes to store() function of NewsController class.

laravel-root/resources/views/news/create.blade.php

Here’s the template to show individual news. The URL will be http://your-site/news/{slug}. This calls show($slug) function of NewsController class.

laravel-root/resources/views/news/show.blade.php

Here’s the template to edit news. The edit news form post action goes to update() function of NewsController class.

laravel-root/resources/views/news/edit.blade.php

Download Source Code from GitHub

Hope this helps. Thanks.

Laravel

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed

Comments are closed.