Laravel Simple CRUD Operation

Laravel is one of the demanding web development frameworks nowadays. It’s PHP Framework. Laravel requires little bit PHP knowledge if you don’t have then go through previous PHP Tutorials. Create, Read, Update and Delete (CRUD) are the very basic operations that almost every application has Creating a Laravel Simple CRUD Operation. The complexity of the operations are within the Laravel framework and there is some basic configuration sorts of things which needs to be performed to make this working.

In this tutorial, we will create a Student Details Manager, where you can create new student details, show them as a list on the front page and modify or delete them.

Laravel Simple CRUD Operation


To demonstrate view, add, edit, and delete functionality, we’ll show the student details in laravel 5.5. This sample Laravel CRUD Operation application has the following functionality.

  1. Retrieve Student data from the database and listed on the web page.
  2. Add a new STudent data and insert student data into the database.
  3. Edit student data and update data into the database.
  4. Delete student data from the database.

Simple CRUD Operation in Laravel Programming Pot

Following are the Framework versions and tools we are using for this Tutorial.

  1. Laravel Framework version 5.5
  2. MySQL
  3. Bootstrap version 3.3

Database Table Creation


To store students data a table needs to be created in the database. Follow the below steps to create a students table in the MySQL database.

Laravel has some interesting artisan commands that will make your work a lot easier. If you are looking to create a CRUD application, Laravel has got a single artisan command that will create Model against your table, a migration file to create the table and also a Resource Controller. Resource Controller in Laravel will have all the necessary methods in place that are required to create the Laravel CRUD operation.

Let’s start by running the laravel command.

php artisan make:model Student -m

This command tell’s the artisan to create a Model named Student and -m denoted Modelwhich means along with the Model file this will also generate the migration file that will create the database table called students.

Open the database/migrations/xxxxxx_create_students_table.php file and add the fields to store the basic information:

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->increments('id');
	    $table->integer('roll');
	    $table->string('name',100);
	    $table->biginteger('phone');
	    $table->string('email')->unique();
	    $table->text('address');
            $table->timestamps();
        });
    }

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

Use migrate Artisan command to run the migrations (to make the table in database).

php artisan migrate

# Setting up the Routes


Now let’s create the routes that will match our controller methods for all of the required actions like create, show, update, destroy, and edit.

Add this following line to your web.php file under routes directory.

// Route with Resource Controller
Route::resource('laravel-simple-crud', 'CRUDController');

# Creating Model


Our Model looks like following:

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    //
}

We don’t want to do anything in the model for now.

# Creating Resource Controller


Controllers are stored in the directory used app/Http/Controllers to group request handling logic into a single class. To handle all the student details related request, define a CRUDController by creating a app/Http/Controllers/CRUDController.php file.The CRUDController has the following methods to handle Laravel CRUD Operations.

index() – Retrieve students data from the database via Student model and load the student’s list view.

details() – Get the students details by ID and load the student’s details view.

add() – Load the students adding form view.

insert() – Validate submitted post data and insert into the database via Student model, and redirect the user to the posts list page.

show() – It Shows the individual data of the student through the unique id.

edit() – Load the post editing form view.

update() – Validate submitted students data and update respective students data, and redirect the user to the student’s list page.

delete() – Delete existing students data from the database via Student model and redirect the user to the posts list page.

The CRUDController code looks like these following.

<?php

namespace App\Http\Controllers;

use App\Model\Student;
use Illuminate\Http\Request;

class CRUDController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $students = Student::paginate(10);
        return view('crud.index',compact('students'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // Validate the Field
        $this->validate($request,[
            'name'=>'required',
            'roll'=>'required',
            'email'=>'required',
            'phone'=>'required',
            'address'=>'required',
        ]);
        $student = new Student();
        $student->roll=$request->roll;
        $student->name=$request->name;
        $student->email=$request->email;
        $student->phone=$request->phone;
        $student->address=$request->address;
        $student->save();
        return redirect()->route('laravel-simple-crud.index')->with('message','New Student Created Successfull !');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $student = Student::find($id);
        return view('crud.read',compact('student'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $student = Student::find($id);
        return view('crud.edit',compact('student'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // Validate the Field
        $this->validate($request,[
            'name'=>'required',
            'roll'=>'required',
            'email'=>'required',
            'phone'=>'required',
            'address'=>'required',
        ]);
        $student = Student::find($id);
        $student->roll=$request->roll;
        $student->name=$request->name;
        $student->email=$request->email;
        $student->phone=$request->phone;
        $student->address=$request->address;
        $student->save();
        return redirect()->route('laravel-simple-crud.index')->with('message','Student Updated Successfull !');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $student = Student::find($id)->delete();
        return back()->with('message','Student Deleted Successfull !');
    }
}

# Creating Views and Layout


Since we have four GET methods in our routes which corresponds to the four pages, we will create a new directory under our resources >> views folder named crud and we will now create our view files named create.blade.php , edit.blade.php, index.blade.php , read.blade.php and main.blade.php which include all the main HTML layouts structures and all others view are extends this main view by using the keyword @extends.

# For Example: @extends(‘crud.main’)

We are using Twitter Bootstrap v 3.3 for the consistent layout for our views. Since we are more focused on creating the Laravel Simple CRUD Operation in this tutorial, we will not cover the details of extending the layout.

Following are the files which we have created in our views folder.

Laravel Simple CRUD Operation

For this  Laravel Simple CRUD Operation, we’ll create a custom layout. Create a resources/views/crud/main.blade.php file and place the webpage HTML except for the main content. And this also extends all others views.

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="{{ asset('assets/css/bootstrap.css') }}">

    <title>Laravel CRUD</title>
  </head>
  <body>
    
   
    @section('main-content')

    // Here comes the extended codes

    @show

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script type="text/javascript" src="{{ asset('assets/js/bootstrap.min.js') }}"></script>
  </body>
</html>

Views


1. index.blade.php:

This view listed the student data with details, add, edit, and delete links in one Table.

// Extends the main.blade.php view 
@extends('crud.main')
   
@section('main-content')
   
   <div class="container">
  <div class="jumbotron">
    <h1>Laravel Simple CRUD Operation</h1>
    <p>Laravel Simple CRUD Operations With Student Data.</p>
  </div>
     @if(Session::has('message'))
     <p class="alert alert-success">{{ Session::get('message') }}</p>
     @endif
 <div class="panel panel-primary">
      <div class="panel-heading">
	<a href="{{ route('laravel-simple-crud.create') }}" data-toggle="modal" data-target="#addModal" class="btn btn-default btn-sm"><i class="glyphicon glyphicon-plus"></i> Add New</a>
      </div>
      <div class="panel-body">
	 	<table class="table table-hover table-bordered table-stripped">
	 		<thead>
	 			<tr>
	 			<th>S.N</th>
	 			<th>Name</th>
	 			<th>Roll No.</th>
	 			<th>Phone</th>
	 			<th>Email</th>
	 			<th>Address</th>
	 			<th style="width:200px;">Action</th>
	 			</tr>
	 		</thead>
	 		<tbody>
	 		    @foreach ($students as $student)
	 			<tr>
	 			<td>{{ $loop->index+1 }}</td>
	 			<td>{{ $student->name }}</td>
	 			<td>{{ $student->roll }}</td>
	 			<td>{{ $student->phone }}</td>
	 			<td>{{ $student->email }}</td>
	 			<td>{{ $student->address }}</td>
	 			<td>
	 		<form  method="post" action="{{ route('laravel-simple-crud.destroy',$student->id) }}" class="delete_form">
                	        {{ csrf_field() }}
                		{{ method_field('DELETE') }}
                		<a href="{{ route('laravel-simple-crud.edit',$student->id) }}" class="btn btn-xs btn-primary">Edit</a>
                		
	 			<a href="{{ route('laravel-simple-crud.show',$student->id) }}" class="btn btn-xs btn-success">View</a>

                        <button class="btn btn-xs btn-danger" type="submit" onclick="return confirm('Are You Sure? Want to Delete It.');">Delete</button>
                	</form>
	 		</td>
	 		</tr>
	 		@endforeach
	 		</tbody>
	 	</table>
	 	<p class="pull-right">
	 	{{ $students->links() }}
	 	</p>
   	  </div>
    </div>
</div>
    
@endsection

 2. read.blade.php :

This view shows the details information about a particular single student.

// Extends the main.blade.php view 
@extends('crud.main')
   
@section('main-content')
   
   <div class="container">
  <div class="jumbotron">
    <h1>Laravel Simple CRUD Operation</h1>
    <p>Laravel Simple CRUD Operations With Student Data.</p>
  </div>
 <div class="panel panel-success">
      <div class="panel-heading">
      	View Student Details
      </div>
      <div class="panel-body">
			  <div class="row">
			  	<div class="col-md-4">
			  	<div class="form-group">
				    <label for="roll">Roll Number</label>
				    <input type="text" disabled value="{{ $student->roll }}" class="form-control" placeholder="Roll Number" name="roll" id="email">
				 </div>
			  	</div>
			  	<div class="col-md-8">
			  	<div class="form-group">
				    <label for="roll">Student Name</label>
				    <input type="text" disabled value="{{ $student->name }}" class="form-control" placeholder="Student Name" name="name" id="name">
				 </div>
			  	</div>
			  	<div class="col-md-6">
			  	<div class="form-group">
				    <label for="email">Email</label>
				    <input type="email" disabled value="{{ $student->email }}" class="form-control" placeholder="Email" name="email" id="email">
				 </div>
			  	</div>
			  	<div class="col-md-6">
			  	<div class="form-group">
				    <label for="phone">Phone</label>
				    <input type="text" disabled value="{{ $student->phone }}" class="form-control" placeholder="Phone" name="phone" id="phone">
				 </div>
			  	</div>
			        <div class="col-md-12">
			  	<div class="form-group">
				    <label for="address">Address</label>
				    <input type="text" disabled value="{{ $student->address }}" class="form-control" placeholder="Address" name="address" id="address">
				 </div>
			  	</div>
			  </div>
			  <a href="{{ route('laravel-simple-crud.index') }}" class="btn btn-danger">Back</a>
   	  </div>
    </div>
</div>
    
@endsection

3. create.blade.php:

This view shows the form to add the new student details to the database.

// Extends the main.blade.php view 
@extends('crud.main')
   
@section('main-content')
   
   <div class="container">
  <div class="jumbotron">
    <h1>Laravel Simple CRUD Operation</h1>
    <p>Laravel Simple CRUD Operations With Student Data.</p>
  </div>
 <div class="panel panel-success">
      <div class="panel-heading">
      	Create New Student
      </div>
      <div class="panel-body">
      	@if ($errors->any())
			    <div class="alert alert-danger">
			        <ul>
			            @foreach ($errors->all() as $error)
			                <li>{{ $error }}</li>
			            @endforeach
			        </ul>
			    </div>
			@endif
	 	 <form action="{{ route('laravel-simple-crud.store') }}" method="post">
	 	 	{{ csrf_field() }}
			  <div class="row">
			  	<div class="col-md-4">
			  	<div class="form-group">
				    <label for="roll">Roll Number</label>
				    <input type="text" class="form-control" placeholder="Roll Number" name="roll" id="email">
				 </div>
			  	</div>
			  	<div class="col-md-8">
			  	<div class="form-group">
				    <label for="roll">Student Name <span class="required">*</span></label>
				    <input type="text" class="form-control" placeholder="Student Name" name="name" id="name">
				 </div>
			  	</div>
			  	<div class="col-md-6">
			  	<div class="form-group">
				    <label for="email">Email</label>
				    <input type="email" class="form-control" placeholder="Email" name="email" id="email">
				 </div>
			  	</div>
			  	<div class="col-md-6">
			  	<div class="form-group">
				    <label for="phone">Phone</label>
				    <input type="text" class="form-control" placeholder="Phone" name="phone" id="phone">
				 </div>
			  	</div>
			        <div class="col-md-12">
			  	<div class="form-group">
				    <label for="address">Address</label>
				    <input type="text" class="form-control" placeholder="Address" name="address" id="address">
				 </div>
			  	</div>
			  </div>
			  <button type="submit" class="btn btn-primary">Add</button>
			  <a href="{{ route('laravel-simple-crud.index') }}" class="btn btn-danger">Back</a>
			</form> 
   	  </div>
    </div>
</div>
    
@endsection

4. edit.blade.php:

This view shows a form with particular student details information and allows a user to edit and update student details.

// Extends the main.blade.php view 
@extends('crud.main')
   
@section('main-content')
   
   <div class="container">
  <div class="jumbotron">
    <h1>Laravel Simple CRUD Operation</h1>
    <p>Laravel Simple CRUD Operations With Student Data.</p>
  </div>
 <div class="panel panel-success">
      <div class="panel-heading">
      	Edit Student
      </div>
      <div class="panel-body">
      	@if ($errors->any())
			    <div class="alert alert-danger">
			        <ul>
			            @foreach ($errors->all() as $error)
			                <li>{{ $error }}</li>
			            @endforeach
			        </ul>
			    </div>
			@endif
	 	 <form action="{{ route('laravel-simple-crud.update',$student->id) }}" method="post">
	 	 	{{ csrf_field() }}
	 	 	{{ method_field('PATCH') }}
			  <div class="row">
			  	<div class="col-md-4">
			  	<div class="form-group">
				    <label for="roll">Roll Number</label>
				    <input type="text" value="{{ $student->roll }}" class="form-control" placeholder="Roll Number" name="roll" id="email">
				 </div>
			  	</div>
			  	<div class="col-md-8">
			  	<div class="form-group">
				    <label for="roll">Student Name</label>
				    <input type="text" value="{{ $student->name }}" class="form-control" placeholder="Student Name" name="name" id="name">
				 </div>
			  	</div>
			  	<div class="col-md-6">
			  	<div class="form-group">
				    <label for="email">Email</label>
				    <input type="email" value="{{ $student->email }}" class="form-control" placeholder="Email" name="email" id="email">
				 </div>
			  	</div>
			  	<div class="col-md-6">
			  	<div class="form-group">
				    <label for="phone">Phone</label>
				    <input type="text" value="{{ $student->phone }}" class="form-control" placeholder="Phone" name="phone" id="phone">
				 </div>
			  	</div>
			        <div class="col-md-12">
			  	<div class="form-group">
				    <label for="address">Address</label>
				    <input type="text" value="{{ $student->address }}" class="form-control" placeholder="Address" name="address" id="address">
				 </div>
			  	</div>
			  </div>
			  <button type="submit" class="btn btn-success">Update</button>
			  <a href="{{ route('laravel-simple-crud.index') }}" class="btn btn-danger">Back</a>
			</form> 
   	  </div>
    </div>
</div>
    
@endsection

# Test the Application


Now it’s time to test the Laravel Simple CRUD Operation. Run the Posts controller URL (http://example.com/laravel-simple-crud) on the browser, you’ll see the student list with add, edit and delete links. and also show the demo here and download the project code. You can also view the demo video about this post on youtube and also show the demo below.

View Demo

Also Read:

  1. Laravel Create Migration
  2. Laravel API Documentation Generator

6 thoughts on “Laravel Simple CRUD Operation”

  1. Very good post. Very helpful. Thank you for sharing.

    1. Thank You so much. Keep staying with us.

  2. Ammy thakur says:

    plz help mecode this problem
    contact 9719797907

    1. What type of problem do you have???

  3. Ammy thakur says:

    create page working and index ,edit, read, page not working plzzz help m sir

    1. What is the problem please send me the screen shot of your errors.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.