laravel 6 crud app

CRUD Operations in Laravel 6 Tutorial with Example

In this article, you will learn how to build a simple Laravel 6 CRUD (CREATE-READ-UPDATE-DELETE) app. We will walk through every step of building the application.

You can check the demo before starting this Tutorial.

Laravel is one of the most popular PHP frameworks. It is growing so fast. It comes up with a variety of functionalities that you can leverage.

Laravel Overview

  • MVC Architecture
  • Blade Templating Engine
  • Eloquent ORM
  • Routing
  • Facades
  • Middleware
  • Built-in Testing
  • Great Documentation
  • Large community

and the list goes on.

Prerequisites

  • Node and NPM (Latest Versions)
  • Latest PHP installed (>=7.3)
  • Composer Dependency Manager. Download it from here.

Creating Laravel Project

In order to create a fresh installation of Laravel, open command prompt and type the following command:

composer create-project --prefer-dist laravel/laravel crudapp

The above given command will create a fresh installation of the Laravel project in your current directory in command prompt.

After the installation of the Laravel project, change your directory to your Laravel project by using the following command:

cd crudapp

Open the code editor of your choice and find the file called .env. In this file, you will store the private environment variables for your app.

For this article, I will use sqlite as database.

Database Setup

  1. Open the .env file.
  2. Set DB_CONNECTION to sqlite on line # 9 of .env file.
  3. Remove the lines DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME, and DB_PASSWORD.
  4. Open the file database.php located at config>database.php
  5. Change default database connection to sqlite from mysql.
    Change this line: 'default' => env('DB_CONNECTION', 'mysql'),
    to 'default' => env('DB_CONNECTION', 'sqlite'),
  6. In the database folder, create a file named database.sqlite

The database is successfully setup now.

Creating Routes

Creating routes is the right way to start developing your app. It will make clear that what models, views and controllers you will need.

Requirements of the app

For this app, a user should be able to:

  • View a list of employees
  • Create an Employee
  • Edit Employee
  • Update Employee
  • Remove Employee

To achieve this, we need to create the following routes:

Get Requests

An HTTP GET request is made when a user wants to view a specific resource or resources. Following are the GET request routes:

  • / – route shows homepage
  • /employees – shows list of all employees
  • /employee/{id} – views a specific employee’s record
  • /create – shows a form to create employee
  • /edit/employee/{id}– shows a form to edit specific employee
  • /employee/{id}/– delete deletes and redirects to the home page

POST Requests

Normally, when there is some change to be made on the server, we use HTTP POST Request. Following are the POST request routes:

  • /create – Creates a new employee
  • /update – Updates the employee

Open routes/web.php file and replace the file with the following piece of code:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
})->name('home');

Route::get('/employees', 'EmployeeController@index')->name('employees.index');
Route::get('/employees/{id}/edit','EmployeeController@edit')->name('employees.edit');
Route::get('/employees/{id}/delete','EmployeeController@destroy')->name('employees.destroy');
Route::get('/create','EmployeeController@create')->name('employees.create');
Route::post('/create','EmployeeController@store')->name('employees.store');
Route::post('/employee/update','EmployeeController@update')->name('employees.update');

Understanding Route

Let’s analyze a route’s structure:

Route::get('/employees', 'EmployeeController@index')->name('employees.index');

This will create a route at 127.0.0.1/employees. If this route is triggered, then the index function of EmployeeController will be called.

Notice the {id} route parameter. This situation occurs when you want to select a specific resource, in our case, a specific employee with id 2. It helps in editing, deleting the resource.

Creating Views

In the MVC Architecture, View is something what the user sees. In simple words, it is the User Interface (UI). Laravel ships with a default view named welcome.blade.php. All the view files in Laravel have an extension .blade.php since Laravel uses the Blade Template Engine. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

A Templating Engine is an elegant way of outputting your dynamic data in your View/html code. Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

Required Views

  • show list of all employees
  • add a new employee
  • edit an existing employee

Let’s add the above given views. Add a folder named layouts inside views folder. Add a folder inside views folder named employee. Create the following files and add the code:

master.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>@yield('title')</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  @yield('content')
</div>

</body>
</html>

index.blade.php

@extends('layouts.master')
@section('title','Employees Index')
@section('content')
	<div class="row">
		<div class="col-sm-12">
			<table class="table">
				<tr>
					<th>ID</th>
					<th>First Name</th>
					<th>Last Name</th>
					<th>Department</th>
					<th>Phone No.</th>
				</tr>
				@foreach($employees as $employee)
					<tr class = "text-center">
						<td>{{ $employee->id }}</td>
						<td>{{ $employee->firstname }}</td>
						<td>{{ $employee->lastname }}</td>
						<td>{{ $employee->department }}</td>
						<td>{{ $employee->phone }}</td>
						<td><a href="{{route('employees.edit',['id'=>$employee->id])}}" class = "btn btn-info">Edit</a></td>
						<td><a href="{{route('employees.destroy',['id'=>$employee->id])}}" class = "btn btn-danger">Delete</a></td>
					</tr>
				@endforeach
			</table>
		</div>
	</div>
@endsection

create.blade.php

@extends('layouts.master')
@section('title','Create Employee')
@section('content')
	<div class="row mt-5">
		<div class="col-sm-8 offset-sm-2">
			<form action="{{route('employees.store')}}" method = "post">
				@csrf
				<div class="form-group">
					<label for="firstname">Firstname:</label>
					<input type="text" name = "firstname" id = "firstname" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="lastname">Lastname:</label>
					<input type="text" name = "lastname" id = "lastname" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="department">Department:</label>
					<input type="text" name = "department" id = "department" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="phone">Phone Number:</label>
					<input type="text" name = "phone" id = "phone" class="form-control" required>
				</div>
				<button type = "submit" class = "btn btn-success">Submit</button>
			</form>
		</div>
	</div>
@endsection

edit.blade.php

@extends('layouts.master')
@section('title','Edit Employee')
@section('content')
	<div class="row">
		<div class="col-sm-8 offset-sm-2">
			<form action="{{route('employees.update')}}" method = "post">
				@csrf
				<div class="form-group">
					<label for="firstname">Firstname:</label>
					<input type="text" name = "firstname" id = "firstname" class="form-control" required value = "{{$employee->firstname}}">
				</div>
				<div class="form-group">
					<label for="lastname">Lastname:</label>
					<input type="text" name = "lastname" id = "lastname" class="form-control" required value = "{{$employee->lastname}}">
				</div>
				<div class="form-group">
					<label for="department">Department:</label>
					<input type="text" name = "department" id = "department" class="form-control" required value = "{{$employee->department}}">
				</div>
				<div class="form-group">
					<label for="phone">Phone Number:</label>
					<input type="text" name = "phone" id = "phone" class="form-control" required value = "{{$employee->phone}}">
				</div>
				<input type="hidden" name="id" value = "{{$employee->id}}">
				<button type = "submit" class = "btn btn-success">Submit</button>
			</form>
		</div>
	</div>
@endsection

Creating Model and Database Migration File

In Laravel, a Model basically represents a table in the database. A database migration file is used to tell the schema of the table. We can simply create a model with its relevant migration file with the following command:

php artisan make:model Employee -m

The above command will create a model Employee and its migration file.

First, open the migration for employees table file. It is located in database/migrations folder and replaces with the following code:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateEmployeesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->string('department');
            $table->string('phone');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('employees');
    }
}

Now, open the Employee.php model. It is available in app folder and add the following line. The following line tells the laravel that these fields of the model are fillable and mass assignment can be done on these.

Model.php

protected $fillable = ['firstname','lastname', 'description', 'phone'];

Now, run the following command to run the migrations:

php artisan migrate

Setting Up the Controller

Create a controller named EmployeeController by typing the following command in the terminal or cmd:

php artisan make:controller EmployeeController

Controller in MVC architecture is responsible for taking input from the user and interacting with model to get the required data for the view. It can also be used to validate the input.

Open the EmployeeController file which can be found at app/http/controllers and paste the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Employee;

class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //Show all employees from the database and return to view
        $employees = Employee::all();
        return view('employee.index',['employees'=>$employees]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //Return view to create employee
        return view('employees.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //Persist the employee in the database
        //form data is available in the request object
        $employee = new Employee();
        //input method is used to get the value of input with its
        //name specified
        $employee->firstname = $request->input('firstname');
        $employee->lastname = $request->input('lastname');
        $employee->department = $request->input('department');
        $employee->phone = $request->input('phone');
        $employee->save(); //persist the data
        return redirect()->route('employees.index')->with('info','Employee Added Successfully');
    }



    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //Find the employee
        $employee = Employee::find($id);
        return view('employee.edit',['employee'=> $employee]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        //Retrieve the employee and update
        $employee = Employee::find($request->input('id'));
        $employee->firstname = $request->input('firstname');
        $employee->lastname = $request->input('lastname');
        $employee->department = $request->input('department');
        $employee->phone = $request->input('phone');
        $employee->save(); //persist the data
        return redirect()->route('employees.index')->with('info','Employee Updated Successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //Retrieve the employee
        $employee = Employee::find($id);
        //delete
        $employee->delete();
        return redirect()->route('employees.index');
    }
}

The code is explained with comments.

With this effort, you have created a single table simple CRUD app in Laravel.

Let’s take a look at demo. Start up the server by typing the following command in the project directory:

php artisan serve

All done. Please comment if you find any difficulty. We’ll love to help you.

Here’s another related article you might be interested:

LARAVEL 6 STRIPE PAYMENT INTEGRATION TUTORIAL

Similar Posts

5 Comments

  1. Hi,

    Great tutorials. Just a small correction.

    In EmployeeController.php, it is mentioned as

    public function create()
    {
    //Return view to create employee
    return view(’employees.create’);
    }

    It should be

    public function create()
    {
    //Return view to create employee
    return view(’employee.create’);
    }

    Kindly change it. Thanks.

  2. i have done every thing as said above . But showing Fatal error . Tell me how i run it in browser ????

  3. hi this is mudasir abbas turi you a have given well structure of the crude operation but i m confused in structure that is where to place the edit.blade.php in folder view or the folder which you have said to create like employ and layout

Comments are closed.