Hello Devs,
In this tutorial, we will learn Laravel 8 CRUD Tutorial Example From Scratch
In this section, we will see an example of how to create crud (Create, Read, Update and Delete) in laravel 8.
Follow this step-by-step guide below.
Step 1 : Install Laravel 8
composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Create Migration
php artisan make:migration create_posts_table --create=posts
put the below code in your migration file to create a posts table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->longText('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
run this migration by following command:
php artisan migrate
Step 4: Add Resource Route
routes/web.php
use App\Http\Controllers\PostController;
Route::resource('posts',PostController::class);
Step 5: Add Controller and Model
php artisan make:controller PostController --resource --model=Post
create seven methods by default as bellow methods:
- index()
- create()
- store()
- show()
- edit()
- update()
- destroy()
app/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::latest()->paginate(5);
return view('posts.index',compact('posts'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
Post::create($request->all());
return redirect()->route('posts.index')
->with('success','Post created successfully.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return view('posts.show',compact('post'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('posts.edit',compact('post'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'description' => 'required',
]);
$post->update($request->all());
return redirect()->route('posts.index')
->with('success','Post updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index')
->with('success','Post deleted successfully');
}
}
app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'description',
];
}
Step 6: Add Blade Files
create following bellow blade file:
- layout.blade.php
- index.blade.php
- create.blade.php
- edit.blade.php
- show.blade.php
resources/views/posts/layout.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 CRUD Application - rathorji.in</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
</head>
<body style="background: #e2e2e2;">
<div class="container">
<div class="row">
<div class="col-md-10 offset-1">
@yield('content')
</div>
</div>
</div>
</body>
</html>
resources/views/posts/index.blade.php
@extends('posts.layout')
@section('content')
<div class="card mt-5">
<div class="card-header">
<h2>Laravel 8 CRUD Example from scratch - rathorji.in</h2>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-12 mt-1 mr-1">
<div class="float-right">
<a class="btn btn-success" href="{{ route('posts.create') }}"> Create New Post</a>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-lg-12">
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
</div>
<div class="col-lg-12">
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Title</th>
<th>Description</th>
<th width="280px">Action</th>
</tr>
@foreach ($posts as $post)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $post->title }}</td>
<td>{{ \Str::limit($post->description, 50) }}</td>
<td>
<form action="{{ route('posts.destroy',$post->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('posts.show',$post->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('posts.edit',$post->id) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
@endforeach
</table>
{!! $posts->links() !!}
</div>
</div>
</div>
</div>
@endsection
resources/views/posts/create.blade.php
@extends('posts.layout')
@section('content')
<div class="card mt-5">
<div class="card-header">
<h2>Laravel 8 CRUD Example from scratch - rathorji.in</h2>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-12 mt-1 mr-1">
<div class="float-right">
<a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-lg-12">
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
</div>
<div class="col-lg-12">
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Title:</strong>
<input type="text" name="title" class="form-control" placeholder="Title">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Description:</strong>
<textarea class="form-control" rows="6" name="description" placeholder="Description"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
resources/views/posts/edit.blade.php
@extends('posts.layout')
@section('content')
<div class="card mt-5">
<div class="card-header">
<h2>Laravel 8 CRUD Example from scratch - rathorji.in</h2>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-12 mt-1 mr-1">
<div class="float-right">
<a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-lg-12">
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
</div>
<div class="col-lg-12">
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{ route('posts.update',$post->id) }}" method="POST">
@csrf
@method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Title:</strong>
<input type="text" name="title" value="{{ $post->title }}" class="form-control" placeholder="Title">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Description:</strong>
<textarea class="form-control" style="height:150px" name="description" placeholder="Description">{{ $post->description }}</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
resources/views/posts/show.blade.php
@extends('posts.layout')
@section('content')
<div class="card mt-5">
<div class="card-header">
<h2>Laravel 8 CRUD Example from scratch - rathorji.in</h2>
</div>
<div class="card-body">
<div class="row">
<div class="col-lg-12 mt-1 mr-1">
<div class="float-right">
<a class="btn btn-primary" href="{{ route('posts.index') }}"> Back</a>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-lg-12">
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
</div>
<div class="col-lg-12">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Title:</strong>
{{ $post->title }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Description:</strong>
{{ $post->description }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
@endsection
run bellow command for quick run:
php artisan serve
open bellow URL on your browser:
localhost:8000/posts
May this example help you.