Tuesday, 3 November 2015

Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using resource controllers. Resource Controllers can make life much easier and takes advantage of some cool Laravel routing techniques. Today, we’ll go through the steps necessary to get a fully functioning CRUD application using resource controllers.
For this tutorial, we will go through the process of having an admin panel to create, read, update, and delete (CRUD) a resource. Let’s use nerds as our example. We will also make use of Eloquent ORM.
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:
    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.
    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.
    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 @yieldmethod 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.
    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.
    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 foundhere.

    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.


    Simple CRUD in Laravel Framework

    Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using re...