Laravel5.7 CRUD Operations Examples from Scratch.

We learned to set up our database and perform initial database migration in previous blog. You will need to go through this post to do your database setup. After doing the initial setup we will jump straight in making data models, controllers, routes and views for performing crud operation:

Laravel5.7 : MySQL Setup and Initial Migration. [Solved] “Illuminate\Database\QueryException : could not find driver (MySQL)”

In this blog we will create a simple laravel webapp which will perform CRUD operations in a student’s database.

Create a Model

In your terminal type this command to create a model:

php artisan make:model Student -m

This will create a model file and a data migration file: Student.php (Model) and create_students_table (migration file). Migration file will have appended datetime as its prefix. You can find your model Student.php in app folder. The migration file is stored inside database/migration.

Create Schema of Student Table for Migration in create_student_table.php

<?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->string('name');
            $table->integer('reg_no')->unique();
            $table->string('email')->unique();
            $table->string('school');
        $table->string('department');
        $table->timestamps();
        });
    }

Student Table will have following columns: id, name, reg_no, email, school, department and timestamps. Perform data migration from command line by command:

php artisan migrate

In your terminal now let's check the tables if they are present or not. With your relevant information which you added during the database setup enter your database name.


mysql -u root -p
show databases;
use databasename;
describe tablename;

For my demo purpose the table name is students. So my student table will look like this:

mysql> describe students;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255)     | NO   |     | NULL    |                |
| reg_no     | int(11)          | NO   | UNI | NULL    |                |
| email      | varchar(255)     | NO   | UNI | NULL    |                |
| school     | varchar(255)     | NO   |     | NULL    |                |
| department | varchar(255)     | NO   |     | NULL    |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
8 rows in set (0.27 sec)

We have our database and table ready we should now create view to add information in the database.

Create View

In your project inside the resources folder you will find your views. Inside the views folder create a file create.blade.php.

<!– create.blade.php –>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet">
<script data-src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
</head>
<body>
<div class="container">
<h2>Student Information Manager</h2><br/>
<form method="post" action="{{url('students')}}" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Name">Name:</label>
<input type="text" class="form-control" name="name">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Registration">Registration Number:</label>
<input type="text" class="form-control" name="reg_no">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Email">Email:</label>
<input type="text" class="form-control" name="email">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="School">School:</label>
<select name="school">
<option value="Science">Science</option>
<option value="Engineering">Engineering</option>
<option value="Medicine">Medical Science</option>
<option value="Management">Management</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<lable>Department</lable>
<select name="department">
<option value="CS">Computer Science</option>
<option value="CE">Computer Engineering</option>
<option value="ME">Mechanical Engineering</option>
<option value="EE">Electrical Engineering</option>
<option value="Civil">Civil Engineering</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4" style="margin-top:60px">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</body>
</html>

view raw
create.blade.php
hosted with ❤ by GitHub

Create Controller

As we will click the submit button there should be a function which incorporates the logic to save that student information in the database. So in your terminal type:

php artisan make:controller StudentController --resource

This will create a StudentController.php file inside app/Http/Controller

Create Route

First register this controller within a route in your web.php file which is located inside your routes folder. There is already a default route for ‘/’, add this code too.

Route::resource('students','StudentController');

Now from your terminal look for the routes that are creates:

php artisan route:list
You will get following available routes that are defined inside your Student Controller:
whoami@whoami:~/blog$ php artisan route:list
+--------+-----------+-------------------------+------------------+------------------------------------------------+--------------+
| Domain | Method    | URI                     | Name             | Action                                         | Middleware   |
+--------+-----------+-------------------------+------------------+------------------------------------------------+--------------+
|        | GET|HEAD  | /                       |                  | Closure                                        | web          |
|        | GET|HEAD  | api/user                |                  | Closure                                        | api,auth:api |
|        | GET|HEAD  | students                | students.index   | App\Http\Controllers\StudentController@index   | web          |
|        | POST      | students                | students.store   | App\Http\Controllers\StudentController@store   | web          |
|        | GET|HEAD  | students/create         | students.create  | App\Http\Controllers\StudentController@create  | web          |
|        | GET|HEAD  | students/{student}      | students.show    | App\Http\Controllers\StudentController@show    | web          |
|        | PUT|PATCH | students/{student}      | students.update  | App\Http\Controllers\StudentController@update  | web          |
|        | DELETE    | students/{student}      | students.destroy | App\Http\Controllers\StudentController@destroy | web          |
|        | GET|HEAD  | students/{student}/edit | students.edit    | App\Http\Controllers\StudentController@edit    | web          |
+--------+-----------+-------------------------+------------------+------------------------------------------------+--------------+

Now we will sequentially add codes in StudentController.php controller methods to perform our CRUD Operation:

Create

public function create()
    {
        return view('create');
    }

Whenever the url hits create a view with the name create will be returned by this method written above.

Save To Database

 /**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
    $student= new \App\Student;
    $student->name=$request->get('name');
    $student->reg_no=$request->get('reg_no');
    $student->email=$request->get('email');
    $student->school=$request->get('school');
    $student->department=$request->get('department');
    $student->save();

    return redirect('students')->with('success', 'Students Information saved');
}

Retrieve

We created a view that will add student’s information and store it to the database. We also developed a method in our StudentController to store in the database. Now we will define a method to list the student information in a single page. Immediately after clicking the submit button we will be able to see the names of students in a index page.

 /**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
    $students=\App\Student::all();
    return view('index',compact('students'));
}

Create index.blade.php

Inside the views folder create index.blade.php folder. For the model that I have created and submitted in the database, following code will list the entries:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Information Detail Page</title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<br />
@if (\Session::has('success'))
<div class="alert alert-success">
<p>{{ \Session::get('success') }}</p>
</div><br />
@endif
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Registration Number</th>
<th>Email</th>
<th>School</th>
<th>Department</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
@foreach($students as $student)
<tr>
<td>{{$student['id']}}</td>
<td>{{$student['name']}}</td>
<td>{{$student['reg_no']}}</td>
<td>{{$student['email']}}</td>
<td>{{$student['school']}}</td>
<td>{{$student['department']}}</td>
<td><a href="{{action('StudentController@edit', $student['id'])}}" class="btn btn-warning">Edit</a></td>
<td>
<form action="{{action('StudentController@destroy', $student['id'])}}" method="post">
@csrf
<input name="_method" type="hidden" value="DELETE">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
</html>

view raw
index.blade.php
hosted with ❤ by GitHub

index

Edit

To edit the information that we added above, we will need to do the following:

  • First define a method in control to redirect to the edit view when we click the edit action.
  • Second we define a method to edit the students information in the StudentController.php
  • Third we will need an actual edit view to change those information

Define Edit redirect method

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

Create A Method to actually update the change in the database

/**
     * Update the specified resource in storage.
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
    $student= \App\Student::find($id);
    $student->name=$request->get('name');
    $student->reg_no=$request->get('reg_no');
    $student->email=$request->get('email');
    $student->school=$request->get('school');
    $student->department=$request->get('department');
    $student->save();
    return redirect('students');   
    }

This will do the update operation in the database from the back end. We now need a User Interface to change the data from the UI. So create a view edit.blade.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="{{asset('css/app.css')}}">
</head>
<body>
<div class="container">
<h2>Edit Student Information</h2><br />
<form method="post" action="{{action('StudentController@update', $id)}}">
@csrf
<input name="_method" type="hidden" value="PATCH">
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" value="{{$student->name}}">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="email">Registration Number:</label>
<input type="text" class="form-control" name="reg_no" value="{{$student->reg_no}}">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="number">Email:</label>
<input type="text" class="form-control" name="email" value="{{$student->email}}">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4" style="margin-left:38px">
<lable>School:</lable>
<select name="school">
<option value="Science" @if($student->school=="Science") selected @endif>Science</option>
<option value="Engineering" @if($student->school=="Engineering") selected @endif>Engineering</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4" style="margin-left:38px">
<lable>Department:</lable>
<select name="department">
<option value="CS" @if($student->department=="Computer Science") selected @endif>Computer Science</option>
<option value="CE" @if($student->department=="Computer Engineering") selected @endif>Computer Engineering</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4" style="margin-top:60px">
<button type="submit" class="btn btn-success" style="margin-left:38px">Update</button>
</div>
</div>
</form>
</div>
</body>
</html>

view raw
edit.blade.php
hosted with ❤ by GitHub

Check all these changes if it has worked or not. Go to your project deployed url and now try to edit the information and slick save. It will work. Now a final component of crude remains i.e. removing of the data entry from the database.

Delete

To delete any entry from the database table, we shouldn’t be creating any extra views. By simply calling the method on clicking the Remove button the entry will be deleted.

 /**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
    $student = \App\Student::find($id);
    $student->delete();
    
    return redirect('students')->with('success','Entry is now deleted');
}

This completes all four CRUD operations from Laravel. Next few information are for the beginners who might be thinking how are the actions performed from the UI are binded with the controllers:

Edit Menu
In index.blade.php the href action for the edit menu calls edit action of StudentController and also passes the student id.

<td><a href=”{{action(‘StudentController@edit’, $student[‘id’])}}” class=”btn btn-warning”>Edit</a></td>

Delete Menu
In index.blade.php, the href action for the delete menu calls destroy action of StudentController passing student id as a parameter.

<td><form action=”{{action(‘StudentController@destroy’, $student[‘id’])}}” method=”post”></td>

%d bloggers like this: