July 09, 2014

Developing CRUD Applications in Laravel 4

Developing CRUD ApplicationS in Laravel 4

In this article I am going to demonstrate how to develop a simple CRUD (Create, Read/Retrieve, Update, and Delete) application in Laravel. Laravel is a popular PHP framework, initially released on Feb 2012 and freely available. In order to understand a framework based on MVC (Model View Controller), it’s better to develop a simple CRUD application in it. CRUD utilizes all three layers of MVC and provides a better understanding about the structure of the framework. So, let’s start our journey through Laravel.

The following topics will be covered in this article:

  • Creating and setting up databases using Laravel migration
  • Creating models and controllers using Artisan (command line tool).
  • Creating views using blade template engine.
  • Creating necessary routes

To Demonstrate CRUD functionality a simple Employee Management System (EMS) will be developed. EMS provides following the features:

  • List all employees. (Read/Retrieve)
  • Create new employee record. (Create)
  • Edit/update employee record. (Update)
  • Delete employee record. (Delete)


It’s assumed that you have installed Laravel successfully on your local system, because Laravel installation is beyond the scope of this article.
You have basic understanding of MVC, PHP and mySQL and have some development experience.

Creating a CRUD Application:

1. Setting up database

The first step for building an EMS is to set up a database. Laravel stores its database configuration in app/config/database.php. Open this file in your favorite text editor and enter your database connection details in connection array.
Create an empty database called “ems” in mySQL using phpMyAdmin or any other tool you want, and set its name in the connection array. In my case, mySQL database is used, but yours could be different so change it accordingly. So the mySQL array will be as follows:

1 'mysql' => array(
2 'driver'    => 'mysql',
3 'host'      => 'localhost',
4 'database'  => ‘ems’,
5 'username'  => 'root',
6 'password'  => '',
7 'charset'   => 'utf8',
8 'collation' => 'utf8_unicode_ci',
9 'prefix'    => '',
10 ),

After setting up database configurations, we will create our database schema using the Laravel migration tool. Migrations control versions of databases and provide consistent and up-to-date schema to all team members. Open the command line interface (on Windows start->run type cmd and press enter) and change the directory to Laravel root installation, in my case its: C:wampwwwlaravel.

NOTE: For all Artisan commands, your directory should be pointing to the Laravel root directory where Laravel is installed like C:wampwwwlaravel.

Run migrate make command using Artisan command line as follows.
C:wampwwwlaravel> php artisan migrate:make ems


It will generate a migration file at app/database/migrations/[current date]_ems.php. This migration file contains two empty methods up() and down().
In the up() method we will define schema for “employees” table and in the drop() method we will delete the “employees” table using a drop command. Our “employees” table consists of four fields: first name, last name, email, and timestamp. This is a simple example:

1 public function up()
2 {
3 Schema::create('employees', function($table)
4            {
5                $table->increments('id');
6                $table->string('first_name', 128);
7                $table->string('last_name', 128);
8                $table->string('email', 128);
9  $table->timestamps();
10            });
11 }
12 public function down()
13 {
14 Schema::drop('employees');
15 }

Update your schema file with the above code and run the following command:
php artisan migrate

Now your database should contain an employee table, and for simplicity the employee table contains just 4 fields.

2. Creating Model

Creating a model in Laravel is very easy. Laravel provides Eloquent ORM that holds all necessary database functions; we just need to extend Eloquent.
Just create Employee.php file in app/model with the following code:

1 <?php
2 class Employee extends Eloquent
3 {
4 }

NOTE: Laravel uses naming conventions to connect particular models with database tables, here the model name is set to ‘Employee’ (singular name) to connect with the ‘Employees’ table. However, to connect with a different database table you can define $table variable with table name inside model class.

3. Creating Controller

The ‘artisan’ command line tool helps us to create controllers with full skeleton code. Just run the ‘make controller’ command by providing controller name as a parameter, and it will create a controller inside app/controllers folder with all the required methods.
php artisan controller:make EmployeesController

A controller created by the ‘make’ command will look like the example below. Just view each method; we will describe them in detail later.

1 <?php
2 class EmployeesController extends BaseController {
3 /**
4 * Display a listing of the resource.
5 *
6 * @return Response
7 */
8 public function index()
9 {
10 //
11 }
12 /**
13 * Show the form for creating a new resource.
14 *
15 * @return Response
16 */
17 public function create()
18 {
19 //
20 }
21 /**
22 * Store a newly created resource in storage.
23 *
24 * @return Response
25 */
26 public function store()
27 {
28 //
29 }
30 /**
31 * Display the specified resource.
32 *
33 * @param  int  $id
34 * @return Response
35 */
36 public function show($id)
37 {
38 //
39 }
40 /**
41 * Show the form for editing the specified resource.
42 *
43 * @param  int  $id
44 * @return Response
45 */
46 public function edit($id)
47 {
48 //
49 }
50 /**
51 * Update the specified resource in storage.
52 *
53 * @param  int  $id
54 * @return Response
55 */
56 public function update($id)
57 {
58 //
59 }
60 /**
61 * Remove the specified resource from storage.
62 *
63 * @param  int  $id
64 * @return Response
65 */
66 public function destroy($id)
67 {
68 //
69 }
70   }

NOTE: By default, all models are available to use inside the controller, so there is no need to explicitly define them.

4. Creating Views with Blade Template Engine

We will require four views: list, edit/update, create and delete employee. We are going to use a simple and powerful blade temple engine provided by Laravel. All blade template files must end with the .blade.php extension. We need some common code that is required on all views, so we will wrap this code in layout template.

Create a new file in app/views with name layout.blade.php and place the following HTML in it. It’s a good idea to put all the views in separate folders. For example, for the employees controller, we should create a folder named ‘employee’ inside view. Put all views related to ‘employee’ in this folder. However, for simplicity, I am creating all views in a root view directory.

1 <!doctype html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <link href="//netdna.bootstrapcdn.com/twitter-bootstrap
6 /2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
7 <style>
8 table form { margin-bottom: 0; }
9 form ul { margin-left: 0; list-style: none; }
10 .error { color: red; font-style: italic; }
11 body { padding-top: 20px; }
12 </style>
13 </head>
14 <body>
15 <div class="container">
16 @if (Session::has('message'))
17 <div class="flash alert">
18 <p>{{ Session::get('message') }}</p>
19 </div>
20 @endif
21 @yield('content')
22 </div>
23 </body>
24 </html>

This is the simple layout for our EMS; we used twitter bootstrap CSS for a better look and feel. Any other view can include this layout by just extending it using a @extends(‘layout’). Blade template provides some basic methods to generate a final page by combining different layouts. Contents of the extending view can be injected in the layout file using the @yield(‘content’) method. The @yield method takes the names of content as a parameter and places contents inside the layout. Content should be defined in a separate view file using the @section method. If a page needs a layout, it must extend the layout. A working of the blade template engine is demonstrated in the diagram below.


Now we are going to create the first page of our application that lists all employees. Create a new file inside the views folder with the name index.blade.php and put the following code in it.

1 @extends('layout')
2 @section('content')
3 <div class="page-header" style="border: 1px solid #0077b3; text-align: center">
4 <h1>EMS <small>Better Employee Management </small> </h1>
5 </p></div>
6 <div class="panel panel-default">
7 <div class="panel-body">
8 <a href="{{ action('EmployeesController@create') }}" class="btn btn-info">Add New Employee</a>
9 </div>
10 </div>
11 @if ($employees->isEmpty())
12 There are no employees! :(
13 @else
14 <table class="table table-striped">
15 <thead>
16 <tr>
17 <th>First Name</th>
18 <th>Last Name</th>
19 <th>Email</th>
20 <th>Actions</th>
21 </tr>
22 </thead>
23 <tbody>
24 @foreach($employees as $employee)
25 <tr>
26 <td>{{ $employee->first_name }}</td>
27 <td>{{ $employee->last_name }}</td>
28 <td>{{ $employee->email }}</td>
29 <td>
30 <a href="{{ action('EmployeesController@edit', $employee->id) }}" class="btn btn-default">Edit</a>
31 <a href="{{ action('EmployeesController@delete', $employee->id) }}" class="btn btn-danger">Delete</a>
32 </td>
33 </tr>
34 @endforeach
35 </tbody>
36 </table>
37 @endif
38 @stop

After creating an index view, we need to update the index method of our controller. Add the following code inside the index method and save it. The php compact method is used to generate an array of employees. Details about the compact method can be found here.

1 // Show a listing of employees.
2       $employees = Employee::all();
3        return View::make('index', compact('employees'));

5. Creating routes

The final step to view the output in a browser is to create routes. Laravel stores most of application routes in app/routes.php. Open routes.php, it contains default root for hello.php.

1 Route::get('/', function()
2 {
3 return View::make('hello');
4 });

Remove the default route and add the following routes. It contains all routes that we need later for our views (create, edit, delete). If we are creating a RESTful controller, then we have to define each route explicitly in routes.php as I did here. The advantage of registering each route in the route file is that we can get the whole site’s URL map using the ‘artisan’ route command.

Another option is to create a resource controller, then there is no need to define each route in routes.php. It’s similar to other php frameworks. A resource route can be created as follows:

1 Route::resource('user', 'UserController');

You can find more details about Laravel routes here.
We have created a route for the model at the beginning; this will help us to use model objects as a parameter for different functions like edit/update.

1 // connect with corresponding model.
2 Route::model('employee', 'Employee');
3 //route for index page, call index method of controller
4 Route::get('/', 'EmployeesController@index');
5 //route for create employee page.
6 Route::get('/create', 'EmployeesController@create');
7 //route for edit employee page.
8 Route::get('/edit/{employee}', 'EmployeesController@edit');
9 //route for delete emplooyee page
10 Route::get('/delete/{employee}', 'EmployeesController@delete');
11 // route for form submission call handleCreate method.
12 Route::post('/create', 'EmployeesController@handleCreate');
13 //route to handle edit form submission
14 Route::post('/edit', 'EmployeesController@handleEdit');
15 //route to handle delete.
16 Route::post('/delete', 'EmployeesController@handleDelete');

Save routes.php and open your project on localhost. In my case it is http://localhost/laravel/. You will be able to see the index page-listing employees with the edit/delete button.
If you are unable to view the index page, enable debugging mode by setting up a debug value to true inside app/config/app.php. If debugging is enabled, you can see specific coding errors instead of general error messages. However when deploying the application to the production environment, make sure to disable debugging mode. If you have done all the steps correctly you should see the following page.

Lavavel 2

Now that we are able to see a list of employees on the index page, let’s quickly go over the magic behind it. When users request the localhost/laravel/ from a browser, Laravel searches the route in the routes.php file. Following the route defined in routes.php will direct the control towards the index method of the employees controller.

1 Route::get('/', 'EmployeesController@index');

The index method is very simple and has just two lines of code.

2 $employees = Employee::all();
3 return View::make('index', compact('employees'));

The Employee:all() method will fetch all employees from the database and assign them to the employees variable. Because we extended our model from Eloquent, we can use the all() method easily. The second line will call the make() method of view class that takes a view name and data array as a parameter. Employee data is compressed using php compact method, and will be available on the index view.
Now, I will briefly explain the index view. It extends from the default layout using @extends(‘layout’) blade function. Then the contents of the index view are defined using @section(‘content’) method. Section contents are injected in place of the @yield(‘content’) method in the layout file. Blade template syntax is used to loop through the employees array and generate list. As you can see, blade syntax is easy and similar to php.

1 {{ $employee->first_name }}

This is equal to php:

2 first_name;?>

Now we are going to implement add the employee functionality.

6. Add Employee

In order to add a new employee, we have to create a new file inside the view folder create.blade.php. Add the following code in this file and save it. I have added a few inline styles to show in my code here as I am not including any external CSS files in this tutorial. However, you may use an external CSS file to apply CSS.

1 @extends(‘layout’)
2 @section(‘content’)
3 <div class=”page-header” style=”border: 1px solid #0077b3;”>
4 <h1>Add New Employee </h1>
5 </div>
6 @if ( $errors->count() > 0 )
7 <div class=”alert alert-danger”>
8 <ul>
9 @foreach( $errors->all() as $message )</p>
10 <li>{{ $message }}</li>
11 @endforeach
12 </ul>
13 </div>
14 @endif
15 <form action=”{{ action(‘EmployeesController@handleCreate’) }}” method=”post” role=”form” >
16 <div class=”form-group”>
17 <label for=”first_name”>First Name</label>
18 <input type=”text” class=”form-control” name=”first_name” />
19 </div>
20 <div class=”form-group”>
21 <label for=”last_name”>Last Name</label><br />
22 <input type=”text” class=”form-control” name=” last_name ” />
23 </div>
24 <div class=”form-group”>
25 <label for=”email”>Email</label><br />
26 <input type=”text” class=”form-control” name=”email” />
27 </div>
28 <input type=”submit” value=”Add” class=”btn btn-primary” />
29 <a href=”{{ action(‘EmployeesController@index’) }}” class=”btn btn-link”>Cancel</a>
30 </form>
31 @stop

The create view also extends the layout like the index view. We have created a form inside contents with a submit button. The form action attribute is defined using the action() method and the handleCreate() method will be responsible for form submission. This method takes from post data, saves in the database and redirects the user to the index page. Populate the handleCreate() method with the following code which is defined in controller:

1           $employee = new Employee;
2           $employee->first_name = Input::get('first_name');
3           $employee->last_name = Input::get('last_name');
4           $employee->email = Input::get('email');
5           $employee->save();
6           return Redirect::action('EmployeesController@index');

Lastly our create() method should load a create view template, so your create method should be as follows.

1 public function create()
2   {
3       // Show the create employee form.
4       return View::make('create');
5   }

NOTE: The route for the create method is created already in the routes.php file.

Now click on the “Add New Employee” button and fill in the employee form. When you click the “Add” button, a new employee will be added to the database and the user will be redirected to the index page.

7. Edit Employee

Like the create functionality, we need a view template file edit.blade.php that contains a form populated with selected employee data. When a user updates their record, the handleEdit() method will get post data and update the employee record in similar fashion. So create edit.blade.php with the following code:

1 @extends(‘layout’)
2 @section(‘content’)
3 <div class=”page-header” style=”border: 1px solid #0077b3;”>
4 <h1>Edit Employee </h1>
5 </div>
6 <form action=”{{ action(‘EmployeesController@handleEdit’) }}” method=”post” role=”form”>
7             <input type=”hidden” name=”id” value=”{{ $employee->id }}”>
8 <div class=”form-group”>
9                    <label for=”first_name”>First Name</label>
10                 <input type=”text” class=”form-control” name=”first_name” value=”{{ $employee->first_name }}” />
11         </div>
12 <div class=”form-group”>
13                  <label for=”last_name”>Last Name</label>
14                  <input type=”text” class=”form-control” name=”last_name” value=”{{ $employee->last_name }}” />
15         </div>
16 <div class=”form-group”>
17                   <label for=”email”>Email</label>
18                   <input type=”text” class=”form-control” name=”email” value=”{{ $employee->email }}” />
19         </div>
20                   <input type=”submit” value=”Save” class=”btn btn-primary” />
21                   <a href=”{{ action(‘EmployeesController@index’) }}” class=”btn btn-link”>Cancel</a>
22     </form>
23 @stop

In your employee controller, change the handleEdit() method with the following code.

1 public function handleEdit()
2    {
3        // Handle edit form submission.
4        $employee = Employee::findOrFail(Input::get('id'));
5        $employee->first_name        = Input::get('first_name');
6        $employee->last_name           = Input::get('last_name');
7        $employee->email                = Input::get('email');
8        $employee->save();
9    return Redirect::action('EmployeesController@index');
10   }

Lastly, change the edit() method with following code and your edit functionality will be complete. The default method created by ‘artisan’ has different parameters, so make sure that $employee will be passed as a parameter to edit function. This employee data is populated on the edit employee form, when a user updates an employee record.

1 public function edit(Employee $employee)
2    {
3          // Show the edit employee form.
4          return View::make('edit', compact('employee'));
5    }

Now click on the edit button in front of the employee record, and it will show the edit page form populated with the selected employee record. Now you can change the employee record, and pressing the save button will save changes and redirect you to the index page.

8. Delete Employee

Last, we have to develop the delete functionality to complete our CRUD application. Like create and edit, we need a delete template file, so we create that first.

1 @extends('layout')
2 @section('content')
3 <div class="page-header" style="border: 1px solid #0077b3;" >
4 <h1>Delete {{ $employee->title }} <small>Do you really want to delete employee?</small></h1>
5 </div>
6 <form action="{{ action('EmployeesController@handleDelete') }}" method="post" role="form">
7 <input type="hidden" name="employee" value="{{ $employee->id }}" />
8 <input type="submit" class="btn btn-danger" value="Yes" />
9 <a href="{{ action('EmployeesController@index') }}" class="btn btn-default">No</a>
10 </form>
11 @stop

After that change, use the handleDelete() method with the following code.

1 public function handleDelete()
2    {
3           // Handle the delete confirmation.
4          $id = Input::get('employee');
5          $employee = Employee::findOrFail($id);
6          $employee->delete();
7          return Redirect::action('EmployeesController@index');
8     }

Lastly, load the delete template file inside the delete () method.

1 public function delete(Employee $employee)
2   {
3       // Show delete confirmation page.
4       return View::make('delete', compact('employee'));
5   }

Now click on the “Delete” button appearing in front of each employee record. It will show a delete template page with a confirmation message, and if you select “Yes” it will delete that record and redirect you to the index page. Although we can achieve a delete functionality without creating a separate view file, for simplicity we created a confirmation page.


In this article I have demonstrated how to develop a basic CRUD application in Laravel. The purpose of this writing was to teach Laravel in an easy way. CRUD applications are a good candidate to demonstrate the structure of MVC’s framework. Laravel is an emerging PHP framework, and has become popular in recent years. Hopefully this article will provide a way to learn the basic structure of the framework in just a few hours.


Interested in what software development options Allshore has to offer your business?



Contact Us

    We take your privacy seriously will only use your personal information to administer your account and provide information and services you've requested. For more
    information, check out our Privacy Policy.