Laravel 9 CRUD Tutorial Example From Scratch

10-Apr-2023

.

Admin

Laravel 9 CRUD Tutorial Example From Scratch

Hi Guys,

In this tutorial, I am going to learn you laravel 9 CRUD operation example. We will implement a crud operation example for beginners in laravel 9 application. I will give you a simple example of how to create crud (Create, Read, Update and Delete) in laravel 9. you will learn crud operation in laravel 9.

Laravel 9 is just released at yesterday, Laravel 9 gives several new features and LTS support. So if you are new to laravel then this tutorial will help you create insert update delete application in laravel 9.

You just need to follow a few steps and you will get basic crud stuff using controller, model, route, bootstrap 4, and blade...

Here I will give you a full example for the crud operation example in laravel 9. So, let's follow a few step to create example of laravel 9 crud application tutorial.

Step 1: Download Laravel


Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app

Step 2: Database Configuration

In second step, we will make database Configuration for example database name, username, password etc for our crud application of laravel 9 So lets open .env file and fill all deatils like as bellow:

.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: Add Migration

we are going to create crud application for post. so we have to create migration for "posts" table using Laravel 9 php artisan command, so first fire bellow command:

php artisan make:migration create_posts_table --create=posts

After this command you will find one file in the following path "database/migrations" and you have to put below code in your migration file for create posts table

database/migrations/create_posts_table.php

<?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');

}

}

Now you have to run this migration by following command:

php artisan migrate

Step 4: Add Route

Here, we need to add a resource route for posts crud application. so open your "routes/web.php" file and add the following route.

routes/web.php

<?php

use App\Http\Controllers\PostController;

/*

|--------------------------------------------------------------------------

| 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::resource('posts',PostController::class);

Step 5: Add Controller and Model

In this step, now we should create a new controller as PostController. So run the below command and create a new controller. bellow controller for create resource controller.

php artisan make:controller PostController --resource --model=Post

After the below command, you will find a new file in this path "app/Http/Controllers/PostController.php".

In this controller will create seven methods by default as bellow methods:

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

So, let's copy the below code and put it on the PostController.php file.

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');

}

}

Ok, so after run bellow command you will find "app/Models/Post.php" and put bellow content in Post.php file:

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

In the last step. In this step, we have to create just blade files. So mainly we have to create a layout file and then create new folder "posts" then create blade files of the crud app. So finally you have to create the following bellow blade file:

1) layout.blade.php

2) index.blade.php

3) create.blade.php

4) edit.blade.php

5) show.blade.php

So let's just create the following file and put bellow code.

resources/views/posts/layout.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel 9 CRUD Application - NiceSnippets.com</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 9 CRUD Example from scratch - NiceSnippets.com</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 9 CRUD Example from scratch - NiceSnippets.com</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 9 CRUD Example from scratch - NiceSnippets.com</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 9 CRUD Example from scratch - NiceSnippets.com</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 Laravel App:

All steps have been done, now you have to type the given command and hit enter to run the laravel app:

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/posts

Output :

Add Page :

Edit Page :

Show Page :

I hope it can help you...

#Laravel 9