Table of contents
In this post, I will show you an example of how to implement a Laravel 8 form validation. W know that this is one of the most important to implement before storing or updating records from your Laravel 8 application. So that we saved a record that is clean and secured to our database. For more information about Laravel validation and their supported rules kindly visit their official documentation.
Â
Below is the step-by-step process on how to implement Laravel validation.
Â
Step 1: Laravel Installation
Before we start we need to install the Laravel 8 application in our local environment. In this example, I'm using XAMPP via Windows. But you're free to use any machine and OS.
Â
In your HTDOCS folder run this command:
composer create-project laravel/laravel laravel-validation --prefer-dist
Â
Once done above command run the below command to point our Laravel 8 project directory.
cd laravel-valdation
Â
Step 2: Database Configuration
If your Laravel project is fresh then you need to update your database credentials. Just open the .env file in your Laravel 8 project.
Â
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
Â
Step 3: Generate Model, Controller, and Migration
To generate model, controller, and migration for our Laravel ajax example kindly run the following command:
php artisan make:model Project -m -c
Â
Step 4: Migration Setup
Let's set up the migration of our projects table see below example code:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProjectsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('projects');
}
}
Â
Now let's run the following command below:
php artisan migrate
Â
Step 5: Setup Model
Here is the code of our project.php model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
use HasFactory;
protected $fillable = [
'title',
'description'
];
}
Â
Step 6: Setup Controller
Below is the code of our ProjectController.php as you can see we are using Response when responding to the successful request.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Project;
use Response;
class ProjectController extends Controller
{
/**
* Display a listing of the resource.
*
*/
public function index()
{
$projects = Project::orderBy('id','desc')->get();
return view('projects.index')->with(compact('projects'));
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('projects.create');
}
/**
* Store a newly created resource in storage.
*
*/
public function store(Request $request)
{
$data = $request->validate([
'title' => 'required|max:70',
'description' => 'required'
]);
$project = Project::create($data);
return redirect('projects')->with('success', 'Project created successfully.');
}
}
Â
Step 7: Setup Routes
Now let's code our routes.php see the whole code below.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProjectController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [ProjectController::class, 'index']);
Route::resource('projects', ProjectController::class);
Â
Step 8: Create Project Layout
Below we create a new folder inside resources/views then create a projects folder. Then create index.blade.php and create.blade.php.
Â
index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Validation</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<style type="text/css">
/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */
main > .container {
padding: 60px 15px 0;
}
</style>
</head>
<body class="d-flex flex-column h-100">
<header>
<!-- Fixed navbar -->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Fixed navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</header>
<!-- Begin page content -->
<main class="flex-shrink-0">
<div class="container">
<h1 class="mt-5">Laravel Validation <a href="{{ route('projects.create') }}" class="btn btn-primary" style="float: right;">Add Project</a></h1>
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<table class="table" id="projects-table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
@foreach($projects as $project)
<tr>
<th scope="row">{{ $project->id }}</th>
<td>{{ $project->title }}</td>
<td>{{ $project->description }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
</body>
</html>
Â
create.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Validation</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
<style type="text/css">
/* Custom page CSS
-------------------------------------------------- */
/* Not required for template or sticky footer method. */
main > .container {
padding: 60px 15px 0;
}
</style>
</head>
<body class="d-flex flex-column h-100">
<header>
<!-- Fixed navbar -->
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="#">Fixed navbar</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav me-auto mb-2 mb-md-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link disabled">Disabled</a>
</li>
</ul>
<form class="d-flex">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
</header>
<!-- Begin page content -->
<main class="flex-shrink-0">
<div class="container">
<h1 class="mt-5">Laravel Validation</h1>
<form action="{{ route('projects.store') }}" method="POST" enctype="multipart/form-data" >
@csrf
@if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
@php
Session::forget('success');
@endphp
</div>
@endif
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input type="text"
value="{{ old('title') }}"
class="form-control"
id="title"
placeholder="Title"
name="title">
@if ($errors->has('title'))
<span class="text-danger">{{ $errors->first('title') }}</span>
@endif
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<input type="text"
value="{{ old('description') }}"
class="form-control"
id="description"
placeholder="Description"
name="description">
@if ($errors->has('description'))
<span class="text-danger">{{ $errors->first('description') }}</span>
@endif
</div>
<button type="submit" class="btn btn-primary" style="float: right;">Save</button>
</form>
</div>
</main>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
</body>
</html>
Â
That's it and don't forget to run the following command after following it:
php artisan serve
Â
Result:
I hope it helps. Thank you for reading :)
Read next