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.

https://gist.github.com/sigdelsanjog/1c17f3869a018ea4d6b50b9c56ce8a7e

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:

https://gist.github.com/sigdelsanjog/b1cf93eb96939746b3611b5cf091e074
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

https://gist.github.com/sigdelsanjog/d083f42da59029417fdba92f55389800

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>

6 comments

Comments are closed.