Laravel 8 CRUD Tutorial Example Step by Step From Scratch
Laravel 8 CRUD Tutorial Example Step by Step From Scratch
Laravel is a PHP-based web framework that has already laid the foundation for web
developers to create a web application without worrying about small things. Laravel provides
MVC(model-view-controller) architecture through which you can quickly build CRUD
applications.
Every six months, the core developer team comes with a newer and improved version of
Laravel; it is a Laravel 8. This post will walk you through how to create a Laravel 8 crud
application fast. If you are a beginner in Laravel, this article will help you create, insert,
update, and delete the model from the Database.
I will use the Visual Studio Code as an editor for this project.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel8crud
DB_USERNAME=root
DB_PASSWORD=root
The username and password will be different for yours based on your database credentials.
Laravel comes with some default migrations like users, password_resets, and
create_failed_jobs table. Now go to the terminal and type the following command to run
your migrations.
php artisan migrate
You can see in your database that these tables are created, and those tables are empty.
1. Game.php model
2. create_games_table migration
// create_games_table.php
The id and timestamp fields are created by Laravel by default. The name and price are our
custom fields that the user can add via the webforms. You can run the migration to create the
table in the database.
In a fresh install of Laravel 8, there is no namespace prefix being applied to your route groups
that your routes are loaded into.
// RouterServiceProvider.php
Route::middleware('web')
->namespace('App\Http\Controllers')
->group(base_path('routes/web.php'));
That is it. Now it can find the controller. If your controller files are elsewhere, then you have
to assign the path in the namespace.
Note here that I have added the –resource flag, which will define six methods inside the
GameController, namely:
<?php
// GameController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class GameController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
You can see that the file contains CRUD operations in the form of different functions. We
will use these functions, one by one, to create crud operations.
The –resource flag will call the internal resource() method by Laravel to generate the
following routes. You can check out the route list using the following command.
// web.php
Route::resource('games', 'GameController');
Once the laravel/ui package has been installed, you may install the frontend scaffolding
using the ui Artisan command.
Now, please run “npm install && npm run dev” to compile your fresh scaffolding.
Inside the views directory, we also need to create a layout file. So, we will create the file
inside the views directory called layout.blade.php. Add the following code in
the layout.blade.php file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Laravel 8 CRUD Tutorial</title>
<link href="{{ asset('css/app.css') }}" rel="stylesheet"
type="text/css" />
</head>
<body>
<div class="container">
@yield('content')
</div>
<script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>
1. create.blade.php
2. edit.blade.php
3. index.blade.php
@extends('layout')
@section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="card uper">
<div class="card-header">
Add Games Data
</div>
<div class="card-body">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif
<form method="post" action="{{ route('games.store') }}">
<div class="form-group">
@csrf
<label for="country_name">Game Name:</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="cases">Price :</label>
<input type="text" class="form-control" name="price"/>
</div>
<button type="submit" class="btn btn-primary">Add Game</button>
</form>
</div>
</div>
@endsection
In this code, we have defined the action which will call the store() method of the
GameController’s method. Remember, we have used the resource controller.
Now, we need to return this create view from the create() method of GameController. So
write the following code inside the GameController’s create() method.
// GameController.php
<?php
// GameController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Game;
Now, write the following code inside the GameController.php file’s store() function.
// GameController.php
We use the $request->validate() method for validation, which receives an array of validation
rules. The
Validation rules[] is the associative array. The key will be the field_name and value being
the validation rules. The second parameter is an optional array for custom validation
messages. Rules are separated with a pipe sign “ | ”. In this example, we are using the most
basic validation rules.
If the validation fails, then it will redirect back to the form page with error messages. If the
validation passes then, it will create the new game and save the game in the database.
In case of errors, we need to loop through those error messages inside the
create.blade.php file, which we have already done it.
If you leave all the form fields empty, then you will find the error message like this image.
As we can see that we got the errors, but if we fill all the correct data, you will still not be
able to save the data into the database because of Mass Assignment Exception.
To prevent the Mass Assignment Exception, we need to add a $fillable array inside the
Game.php model.
<?php
// Game.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
Now, if you fill the correct form fields, then it creates a new row in the database.
// GameController.php
return view('index',compact('games'));
}
@extends('layout')
@section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="uper">
@if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div><br />
@endif
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Game Name</td>
<td>Game Price</td>
<td colspan="2">Action</td>
</tr>
</thead>
<tbody>
@foreach($games as $game)
<tr>
<td>{{$game->id}}</td>
<td>{{$game->name}}</td>
<td>{{$game->price}}</td>
<td><a href="{{ route('games.edit', $game->id)}}" class="btn
btn-primary">Edit</a></td>
<td>
<form action="{{ route('games.destroy', $game->id)}}"
method="post">
@csrf
@method('DELETE')
<button class="btn btn-danger"
type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
<div>
@endsection
We have added two buttons named edit and delete to perform the respective operations.
// GameController.php
Now, create the new file inside the views folder called edit.blade.php and add the following
code.
@extends('layout')
@section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="card uper">
<div class="card-header">
Edit Game Data
</div>
<div class="card-body">
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif
<form method="post" action="{{ route('games.update', $game->id ) }}">
<div class="form-group">
@csrf
@method('PATCH')
<label for="country_name">Game Name:</label>
<input type="text" class="form-control" name="name" value="{{
$game->name }}"/>
</div>
<div class="form-group">
<label for="cases">Game Price :</label>
<input type="text" class="form-control" name="price"
value="{{ $game->price }}"/>
</div>
<button type="submit" class="btn btn-primary">Update
Data</button>
</form>
</div>
</div>
@endsection
Now go to the index page and then go to the edit page of a specific game, and you will see
the form with filled values.
// GameController.php
Now you can update all the data into the database.
Step 11: Create Delete Functionality
To remove data from the database, we will use GameController’s destroy() function.
// GameController.php
The delete() function is provided by Laravel to remove the data from the Database.
<?php
// GameController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Game;
return view('index',compact('games'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'price' => 'required',
]);
$show = Game::create($validatedData);
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$game = Game::findOrFail($id);
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
'price' => 'required'
]);
Game::whereId($id)->update($validatedData);
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$game = Game::findOrFail($id);
$game->delete();
That is it. Now, you can create, read, update, and delete the data in Laravel.
If you are interested in the FrontEnd Javascript framework like Vue with Laravel or Angular
with Laravel, check out the guides like Vue Laravel CRUD example and Angular Laravel
Tutorial Example.
I have put the whole crud operation code on Github so you can check it out as well.