Developing CRUD Applications in Laravel 4

Developing a Simple CRUD Application in Laravel

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)
  • Pre-requisites:

    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:

    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:\wamp\www\laravel.


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


    Run migrate make command using Artisan command line as follows.
    C:\wamp\www\laravel> 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:

    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:

    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.

    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.

    @if (Session::has(‘message’))

    {{ Session::get(‘message’) }}

    @endif @yield(‘content’)

    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.

    LaravlDiagram

    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.

    Add New Employee
    @foreach($employees as $employee) @endforeach
    First NameLast NameEmailActions
    {{ $employee->first_name }}{{ $employee->last_name }}{{ $employee->email }}Edit Delete

    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.

    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.

    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:

    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.

    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.

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

    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.

    This is equal to php:

    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.

      @foreach( $errors->all() as $message )
  • {{ $message }}


  • Cancel

    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:

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

    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:

    Cancel

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

    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.

    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.

    No

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

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

    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.

    Conclusion

    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.

The following two tabs change content below.

Hakeem M.

We are a collaborative company at Allshore Virtual Staffing, and encourage our employees to contribute content such as this.Allshore is a remote staffing agency helping startups in the U.S. hire remote software engineers to work as full-time employees. Allshore provides all technical and managerial support via our client services and technology mentorship teams based in Norman, Okla. Contact Allshore today to schedule a free consultation call with a remote staffing specialist or request a free trial of our services.

Latest posts by Hakeem M. (see all)

  • Developing CRUD Applications in Laravel 4 - Jul

15 Comments

  1. Mike Bailey-Reply
    Oct at 7:20 AM

    Thank you! This tutorial was very helpful.

    The create.blade.php file has an error where the “last_name” field has spaces inside its quotes, causing it not to work. It turned out to be quite instructional however, as I found it quickly after turning Debug on.

  2. Oct at 1:11 AM

    Pretty nice post. I just stumbled upon your weblog and wished to say that I
    have really enjoyed browsing your blog posts.
    After all I will be subscribing to your feed and I hope you write again very soon!

  3. Awesome post.

  4. Felipe Díaz-Reply
    Oct at 7:06 PM

    Thanks you so much , this was exactly what I was looking for

  5. John Alvir-Reply
    Oct at 4:22 PM

    Great Tuts man!

  6. ronnel-Reply
    Oct at 10:56 PM

    Thanks for this great tutorial .

  7. Steven-Reply
    Nov at 10:19 AM

    Awesome, Well written, easy to follow…Question Why then do we need a model if nothing is in it?

  8. Jean-Reply
    Nov at 1:23 PM

    Great tuts +1

  9. farbacan-Reply
    Jan at 9:29 PM

    Very helpful. Thanks.

  10. Xavier-Reply
    Jan at 8:51 PM

    Nice tutorial.
    Very clear.

    Thanks

    • Xavier-Reply
      Jan at 4:14 PM

      Do you try to implement jTable in this tutorial ?
      If yes, someone can share sources ?
      I spend a lot of time but no result.

  11. Feb at 5:22 PM

    Helpful one good job (y)

  12. kinga charles-Reply
    Feb at 3:02 PM

    Good one. Thenx

  13. Rangasamy-Reply
    Apr at 2:30 PM

    Nice Article. Thanks for this great tutorial.

  14. dhanixblue-Reply
    Jul at 11:00 AM

    clear and straight-forward 🙂

Leave A Comment