Laravel 9 CRUD Example Tutorial for Beginners

Laravel 9 CRUD Example Tutorial for Beginners

Last Updated: 24 Nov, 2022

Dear friends, greetings. In this tutorial, we will learn how to implement CRUD operations in laravel version 9. You will get step by step guidance from scratch. At the end of this tutorial, you will be able to create a basic CRUD operation in laravel 9.

How to create CRUD application in laravel 9 with example?

  • Step 1: Install Fresh Laravel 9 Application
  • Step 2: Setup Database Configuration
  • Step 3: Create Database Migration
  • Step 4: Create a Resource Route
  • Step 5: Create Controller and Model
  • Step 6: Create View Pages (Blade Files)
  • Step 7: Run Laravel Application

Now, we will go through all the above steps one by one to achieve our objective.

Step 1: Install Fresh Laravel 9 Application

First of all, lets install a fresh laravel 9 application. Open your terminal and run the following command:

composer create-project laravel/laravel blog

Step 2: Setup Database Configuration

Next, lets update database configuration in .env file as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel9db
DB_USERNAME=dbusername
DB_PASSWORD=dbpassword

Step 3: Create Database Migration

Next, lets create a migration file for posts table using following command:

php artisan make:migration create_posts_table --create=posts

Above command will create a file inside database/migrations directory. Open that file and modify as follows:

<?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('post_title');
            $table->text('post_content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Next, you have to run the below command that will execute the migration file and posts tables will be created in your database:

php artisan migrate

Step 4: Create a Resource Route

Next, lets create a resource route to perform posts CRUD operations. Open routes/web.php file and add following route in it:

<?php

use Illuminate\Support\Facades\Route;
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: Create Controller and Model

Next, lets create a resource controller named PostController and model named Post. In terminal, use following command to achieve this:

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

When you run above command, 2 files will be created:

  • Controller file: app/Http/Controllers/PostController.php
  • Model file: app/Models/Post.php

Controller file has follwing methods:

  • index()
  • create()
  • store()
  • show()
  • edit()
  • update()
  • destroy()

Let's open the PostController.php file and modify it as follows:

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::paginate(10);
        $view_data['posts'] = $posts;
        return view('posts.index')->with($view_data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $view_data['page_title'] = 'Create Post';
        return view('posts.create')->with($view_data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'post_title' => 'required',
            'post_content' => 'required',
        ]);

        $request_data = $request->all();

        Post::create([
            'post_title' => $request_data['post_title'],
            'post_content' => $request_data['post_content']
        ]);

        return redirect()->route('posts.index')->with('success', 'Post created successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {
        return view('posts.show', compact('post'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @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  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Post $post)
    {
        $request->validate([
            'post_title' => 'required',
            'post_content' => 'required',
        ]);

        $post->update($request->all());

        return redirect()->route('posts.index')->with('success','Post updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();

        return redirect()->route('posts.index')->with('success', 'Post deleted successfully');
    }
}

Let's open the Post.php file and modify it as follows:

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;

    protected $fillable = [
        'post_title', 'post_content'
    ];
}

Step 6: Create View Pages (Blade Files)

Next, let's create all the required view files in properly organized folder. We will need following files inside resources/views directory:

  • master.blade.php
  • index.blade.php
  • create.blade.php
  • edit.blade.php
  • show.blade.php

resources/views/posts/master.blade.php

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Laravel 9 CRUD Application Tutorial - W3TechPoint</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
</head>
<body>
	<div class="container p-3 bg-light">
		@yield('content')
	</div>
</body>
</html>

resources/views/posts/index.blade.php

@extends('posts.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-10">
		<h3>Laravel 9 CRUD Application Tutorial</h3>
	</div>
	<div class="col-12 col-md-2 text-end">
		<a class="btn btn-primary" href="{{route('posts.create')}}">Create New Post</a>
	</div>
</div>
@if($message = Session::get('error'))
<div class="row">
	<div class="col-12">
		<div class="alert alert-danger alert-dismissible fade show" role="alert">
		  <strong>{{$message}}!</strong>
		  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
		</div>
	</div>
</div>
@endif
<div class="row">
	<div class="col-12">
		<table class="table table-primary">
		  <thead>
		    <tr>
		      <th scope="col">#</th>
		      <th scope="col">PostTitle</th>
		      <th scope="col">PostContent</th>
		      <th scope="col">Action</th>
		    </tr>
		  	</thead>
		  	<tbody>
	  		@if($posts->count() > 0)
			  	@foreach($posts as $post)
			    <tr>
			      <td>{{$loop->index + 1}}</td>
			      <td>{{$post->post_title}}</td>
			      <td>{{$post->post_content}}</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
		    @else
		    <tr>
		      <td colspan="4">Record not found!</td>
		    </tr>
		    @endif
		  	</tbody>
		</table>
		{!! $posts->links() !!}
	</div>
</div>
@endsection

resources/views/posts/create.blade.php

@extends('posts.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-10">
		<h3>Create New Post</h3>
	</div>
	<div class="col-12 col-md-2 text-end">
		<a class="btn btn-primary" href="{{route('posts.index')}}">Go Back to Posts</a>
	</div>
</div>
@if($errors->any())
<div class="row">
	<div class="col-12">
		<div class="alert alert-danger alert-dismissible fade show" role="alert">
		  <strong>Some error occured!</strong>
		  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
		  <ul>
		  	@foreach($errors->all() as $error)
		  	<li>{{$error}}</li>
		  	@endforeach
		  </ul>
		</div>
	</div>
</div>
@endif
<div class="row">
	<div class="col-12">
		<form method="POST" action="{{route('posts.store')}}">
			@csrf
			<div class="mb-3">
			    <label for="post_title" class="form-label">Post Title</label>
			    <input type="text" class="form-control" id="post_title" name="post_title" placeholder="post title">
		  	</div>
		  	<div class="mb-3">
			    <label for="post_content" class="form-label">Post Content</label>
			    <textarea class="form-control" id="post_content" name="post_content" placeholder="post content"></textarea>
		  	</div>
		  	<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	</div>
</div>
@endsection

resources/views/posts/edit.blade.php

@extends('posts.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-10">
		<h3>Edit Post</h3>
	</div>
	<div class="col-12 col-md-2 text-end">
		<a class="btn btn-primary" href="{{route('posts.index')}}">Go Back to Posts</a>
	</div>
</div>
@if($errors->any())
<div class="row">
	<div class="col-12">
		<div class="alert alert-danger alert-dismissible fade show" role="alert">
		  <strong>Some error occured!</strong>
		  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
		  <ul>
		  	@foreach($errors->all() as $error)
		  	<li>{{$error}}</li>
		  	@endforeach
		  </ul>
		</div>
	</div>
</div>
@endif
<div class="row">
	<div class="col-12">
		<form method="POST" action="{{route('posts.update', $post->id)}}">
			@csrf
			@method('PUT')
			<div class="mb-3">
			    <label for="post_title" class="form-label">Post Title</label>
			    <input type="text" class="form-control" id="post_title" name="post_title" value="{{$post->post_title}}">
		  	</div>
		  	<div class="mb-3">
			    <label for="post_content" class="form-label">Post Content</label>
			    <textarea class="form-control" id="post_content" name="post_content">{{$post->post_content}}</textarea>
		  	</div>
		  	<button type="submit" class="btn btn-primary">Submit</button>
		</form>
	</div>
</div>
@endsection

resources/views/posts/show.blade.php

@extends('posts.master')
@section('content')
<div class="row">
	<div class="col-12 col-md-10">
		<h3>Post Details</h3>
	</div>
	<div class="col-12 col-md-2 text-end">
		<a class="btn btn-primary" href="{{route('posts.index')}}">Go Back to Posts</a>
	</div>
</div>
<div class="row">
	<div class="col-12 mb-3">
		<strong>Post Titile: </strong>
		{!! $post->post_title !!}
	</div>
	<div class="col-12 mb-3">
		<strong>Post Content: </strong>
		{!! $post->post_content !!}
	</div>
</div>
@endsection

Step 7: Run Laravel Application

That's all. You are good to go. Let's run the application using below command:

php artisan server

Next, in your browser, open below URL:

http://localhost:8080/posts

HAPPY LEARNING:)

Laravel 9 CRUD Example Tutorial for Beginners

 

Thank You, Please Share.