Laravel 5.7 CRUD Tutorials with Pagination

by Sam  


What you’ll learn

At the end of this tutorial, you’ll be able to execute CRUD (Create, Retrieve, Update Delete) in Laravel 5.7. You’ll also learn how to add pagination in displaying of records.

Before you proceed, you must:

  • have basic Knowledge in Laravel and OOP
  • know M-V-C  paradigm
  • Installed Server and Composer
  • Met Server Requirements as stated in : https://laravel.com/docs/5.7/installation

Outline

  • Laravel Installation
  • Configure .env file
  • Add Model and migration
  • Create Schema
  • Assign fillable fields
  • Create Resource Controller
  • Register Routes
  • Create, Retrieve, Update, Delete

 

Let’s get started


1. Install Laravel

Open your terminal and download the Laravel Framework by executing the command.

 composer create-project --prefer-dist laravel/laravel school "5.7.*"

We specified the version of laravel to 5.7 for this tutorial.

It takes a few minutes to download. Now, go into the school directory.

 cd school 

After that, start your server.

  php artisan serve 

Open your browser and go to http://localhost:8000

2. Configure your .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=schooldb
DB_USERNAME=root
DB_PASSWORD=

Make sure to change according to your host and database settings.

3.  Model and migration  in one command.

 php artisan make:model --migration Student 

If you want to create model and migration one by one, you can also do it. In this tutorial, I just want to let you know how to do in one command in order to make it faster.

4. Let’s create table schema for students.

Navigate to database » migrations » create_students_table.php and add  additional fields

public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('stud_name');
$table->string('course_name');
$table->string('address');
$table->timestamps();
});
}

After filling out the field data, execute the migration.

 php artisan migrate 

After migrating, the students table will be added to the database together with migrations, password_resets and users table.

5. Assign fillable fields

Go to app» Student.php and add fields as fillable.


namespace App;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
protected $fillable = ['stud_name', 'course_name', 'address'];
}



6. Create Resource Controller for Student

php artisan make:controller StudentController --resource

After executing of the command above, it will generate a file inside app > http > Controllers. Resource controller automatically creates list of methods together with their parameters: index(), create(), store(Request $request), show($id), edit($id), update(Request $request, $id), destroy($id)

In creating of a controller, it is recommended to follow proper convention like, making the first letter to be uppercase and putting “Controller” at the end.

7. Register Controller in our route

Go to routes >> web.php and add our controller in our routes.

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

Then go back to terminal and type,

php artisan route:list

and, should look like this:

8. Create, Retrieve, Update, Delete

Let us add the main layout of our resources >> views >> layouts >> main.blade.php.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> @yield('title') - {{ config('app.name') }}</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}">
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
</html>



After that, we’re going to create students folder inside resources >> views and create create.blade.php file. It will show like this:

8.1. Create

Open StudentController and add the code below.


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

Next, we need to add a form inside create.blade.php.


@extends('layouts.main')

@section('title', 'Create')

@section('content')

<div class="col-md-4 col-md-offset-3 bg-default">

@if ($errors->has('stud_name')) {{ $errors->first('stud_name') }} <br> @endif
@if ($errors->has('course')) {{ $errors->first('course') }} <br> @endif
@if ($errors->has('address')) {{ $errors->first('address') }} <br> @endif

<h3>Create New</h3><hr>
<form action="{{ url('students')}}" method="POST">
@csrf
<label for="studname">Complete Name</label>
<input type="text" name="stud_name" id="studname" class="form-control"><br>
<label for="course">Course</label>
<input type="text" name="course" id="course" class="form-control"><br>
<label for="address">Address</label>
<textarea name="address" id="address" class="form-control" rows="10"></textarea><br>
<input type="submit" value="Submit" name="submit" class="btn btn-primary">
</form>
</div>

@endsection

After that, we have to create a script the will validate the data upon submission and insert it into the database.


public function store(Request $request)
{
$this->validate($request,[
'stud_name' => 'required|max:50',
'course' => 'required|min:2'
],[
'stud_name.required' => 'Please enter the student\'s name ',
'course.min' => 'Course should be minimum of 2 characters'
]);

$crud = new \App\Student([
'stud_name' => $request->get('stud_name'),
'course_name' => $request->get('course'),
'address' => $request->get('address'),
]);

$crud->save();
return redirect('/students');
}

Let’s test the code. Now, start your artisan

 php artisan serve 

and go to http://localhost:8000/students/create . Try to insert dummy data and should have successfully added a new one.

8.2. Retrieve Data

After we’re able to insert data into the database, we can now display it in our page.

Go to StudentController and add the code below:


public function index()
{
$students = \DB::table('students')->paginate(2);
return view('students.index', compact('students'));
}

Next, let’s display the data in our view. Now create file resources >> views >> students >> index.blade.php and copy the code.


@extends('layouts.main')

@section('title', 'Retrieve')

@section('content')
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Student Name</th>
<th>Course</th>
<th>Address</th>
</tr>
</thead>
<tbody>
@foreach($students as $stud)
<tr>
<td>{{ $stud->id }}</td>
<td>{{ $stud->stud_name }}</td>
<td>{{ $stud->course_name }}</td>
<td>{{ $stud->address }}</td>
</tr>
@endforeach
</tbody>
</table>

{{ $students->links() }}

@endsection

Notice that I set the pagination already and limit to 2 per page. You can change this according to what you need to be displayed.

Let’s test the code again. Now, start your artisan and go to http://localhost:8000/students .

8.3 Update Data

Let’s modify our index.blade.php and add additional column into table and put EDIT and DELETE buttons, respectively.


<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Student Name</th>
<th>Course</th>
<th>Address</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
</thead>
<tbody>
@foreach($students as $stud)
<tr>
<td>{{ $stud->id }}</td>
<td>{{ $stud->stud_name }}</td>
<td>{{ $stud->course_name }}</td>
<td>{{ $stud->address }}</td>
<td><a href="{{action('StudentController@edit', $stud->id)}}" class="btn btn-warning">Edit</a></td>
<td>
<form action="{{action('StudentController@destroy', $stud->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>

Next, let’s add script into our edit method inside our StudentController.php


public function edit($id)
{
$stud = \App\Student::find($id);
return view('students.edit', compact('stud','id'));
}

Then, we need to create edit.blade.php inside resources >> students folder and copy the code below:


@extends('layouts.main')
@section('title', 'Update')
@section('content')
<form method="post" action="{{action('StudentController@update', $id)}}">
@csrf
<input name="_method" type="hidden" value="PATCH">
<label for="studname">Complete Name</label>
<input type="text" name="stud_name" id="studname" value="{{ $stud->stud_name }}" class="form-control"><br>
<label for="course">Course</label>
<input type="text" name="course" id="course" value="{{ $stud->course_name }}" class="form-control"><br>
<label for="address">Address</label>
<textarea name="address" id="address" class="form-control" rows="10">{{ $stud->address }}</textarea><br
<input type="submit" value="Submit" name="submit" class="btn btn-primary">
</form>
@endsection

After that, we need to apply changes in our database when the user clicks update. Go to StudentController.php, and copy the code below:


public function update(Request $request, $id)
{
$crud = \App\Student::find($id);
$crud->stud_name = $request->get('stud_name');
$crud->course_name = $request->get('course');
$crud->address = $request->get('address');
$crud->save();
return redirect('/students');
}

Lastly, start your artisan and test it again. If you notice, I didn’t add validation. You can add validation like how I added in create method.

8.4 Delete Data

This is the last operation we need to execute. It’s simpler because we already added delete button above. What we need to do is to add the script below inside your StudentController.


public function destroy($id)
{
$stud = \App\Student::find($id);
$stud->delete();
return redirect('/students');
}

Conclusion

Thank you for reading this guide. I hope you’re able to follow through all of the things above and able to execute CRUD in your local server.

If you have any questions or suggestions, please feel free to comment below.



Leave a Reply

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


Need of a Website?

Maybe you're planning to build a landing page for your website. You might also have a plan to create a web application. I can offer you with an affordable but with good quality services. Don't hesitate to submit your specifications by clicking the button below.

Get Quote