Menu

Crud Application In Laravel 10


Today, I will show you how to create a crud operation in laravel 10. Here I explained simple steps to build the laravel 10 crud application. This example will help you to create laravel crud for beginners. With this example, you will learn the CRUD application in laravel 10.

Laravel 10 is not released yet, So I am using a development branch of laravel 10. In laravel, there are also new features. If you are new to laravel, this tutorial will help you create an insert, update, read and delete operation in laravel.

In this example, I will create a post-crud application using laravel 10. We will create a post table with a title, description, and body column using laravel 10 migration, We will also create a post-Controller, Model, Route, View, Request, and other files related to the post module. We will use the AdminLte template for design.
Let's start the Below steps to create a crud application with laravel 10.
 

Install laravel 10

Our first step is to install laravel 10. We will use the composer command to create the laravel 10 project. Follow the below command to install the project.

composer create-project --prefer-dist laravel/laravel laravel-x dev-master

This command will install the latest laravel project in laravel-x repository. It will install the development master branch. Which is laravel 10.
 

Database Configuration

Our next step is to configure the database for our laravel project. For this, we need to update the database name, username, and password in the .env file. Let's Open .env file and make the below changes.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_x
DB_USERNAME=root
DB_PASSWORD=

 

Create Post module files.

As we know, We need to create a controller, model, and other files for the Post module. For this, we will use a single command to create these files.

php artisan make:model -a

This command will create multiple files as below.

Model [app/Models/Post.php]  

Factory [database/factories/PostFactory.php]  

Migration [database/migrations/2023_01_11_174526_create_posts_table.php]  

Seeder [database/seeders/PostSeeder.php]  

Request [app/Http/Requests/StorePostRequest.php]  

Request [app/Http/Requests/UpdatePostRequest.php]  

Controller [app/Http/Controllers/PostController.php]  

Policy [app/Policies/PostPolicy.php] .

Create column for post table with migration

Our migration file is created with the Model create command. We need to add table columns in the migration file and then run the migration command to create a table in the database. Let's change the migration file as below.
database/migrations/2023_01_11_174526_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string("title");
            $table->text("description");
            $table->longText("body");
            $table->timestamps();
        });
    }

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

 After updating the migration file. We need to run the migration file to create the table in the database with post columns.

php artisan migrate

Create Controller functions

We had already created the Controller and model file for the Post module. Now we need to change the files as below. We have a post controller with default resource functions.
app/Http/Controllers/PostController.php

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

app/Http/Controllers/PostController.php
Update the PostController as below.
 

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(): Response
    {
        $posts = Post::latest()->paginate();
        return response()->view('posts.index',compact('posts'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): Response
    {
        return response()->view('posts.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StorePostRequest $request): RedirectResponse
    {
        $post = new Post;
        $post->title = $request->title;
        $post->description = $request->description;
        $post->body = $request->body;
        if ($post->save()) {
            return redirect()->route('posts.index')->with('status', 'Post Created!');
        }
        return redirect()->route('posts.index')->with('status', 'Something Went Wrong!!!');
    }

    /**
     * Display the specified resource.
     */
    public function show(Post $post): Response
    {
        
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Post $post): Response
    {
        return response()->view('posts.edit',compact('post'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdatePostRequest $request, Post $post): RedirectResponse
    {
        $post->title = $request->title;
        $post->description = $request->description;
        $post->body = $request->body;
        if ($post->save()) {
            return redirect()->route('posts.index')->with('status', 'Post updated!');
        }
        return redirect()->route('posts.index')->with('status', 'Something Went Wrong!!!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Post $post): RedirectResponse
    {
        if ($post->delete()) {
            return redirect()->route('posts.index')->with('status', 'Post Deleted!');
        }
        return redirect()->route('posts.index')->with('status', 'Something Went Wrong!!!');
    }
}

This controller is created with return-type casting functions. This may be due to the development branch or it may continue for version 10.

Create Post Route resource

routes/web.php

<?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::get('/', function () {
    return view('welcome');
});


Route::resource('/posts',PostController::class);

We will add Route::resource('/posts',PostController::class) in the web.php file.

Add Blade Files

Now, we need to create blade files for the crud Application. For this, I will use adminLTE  HTML template for the layout. 

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" and then create blade files of the crud app. So finally you have to create the following bellow blade file:

1) main.blade.php

2) index.blade.php

3) create.blade.php

4) edit.blade.php

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

resources/views/layouts/main.blade.php


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>TemplateBench | Crud Application</title>

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">

    <link rel="stylesheet" href="https://adminlte.io/themes/v3/plugins/fontawesome-free/css/all.min.css">

    <link rel="stylesheet" href="https://adminlte.io/themes/v3/dist/css/adminlte.min.css?v=3.2.0">
</head>
    <body class="hold-transition sidebar-mini">
        <div class="wrapper">

            <nav class="main-header navbar navbar-expand navbar-white navbar-light">

                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
                    </li>
                </ul>
            </nav>


            <aside class="main-sidebar sidebar-dark-primary elevation-4">

                <a href="https://adminlte.io/themes/v3/index3.html" class="brand-link">
                    <img src="https://adminlte.io/themes/v3/dist/img/AdminLTELogo.png" alt="AdminLTE Logo" class="brand-image img-circle elevation-3" style="opacity: .8">
                    <span class="brand-text font-weight-light">TemplateBench</span>
                </a>

                <div class="sidebar">

                    <nav class="mt-2">
                        <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">

                            <li class="nav-item">
                                <a href="#" class="nav-link">
                                    <i class="nav-icon fas fa-tachometer-alt"></i>
                                    <p>
                                        Posts
                                        <i class="right fas fa-angle-left"></i>
                                    </p>
                                </a>
                                <ul class="nav nav-treeview">
                                    <li class="nav-item">
                                        <a href="https://adminlte.io/themes/v3/index.html" class="nav-link">
                                            <i class="far fa-circle nav-icon"></i>
                                            <p>Create</p>
                                        </a>
                                    </li>
                                    <li class="nav-item">
                                        <a href="https://adminlte.io/themes/v3/index2.html" class="nav-link">
                                            <i class="far fa-circle nav-icon"></i>
                                            <p>List</p>
                                        </a>
                                    </li>
                                    
                                </ul>
                            </li>
                        </ul>
                    </nav>

                </div>

            </aside>

            <div class="content-wrapper">
                <section class="content">
                    <div class="container-fluid">
                        @yield('content')
                    </div>
                </section>

            </div>

            <footer class="main-footer">
                <div class="float-right d-none d-sm-block">
                    <b>Version</b> 3.2.0
                </div>
                <strong>Copyright &copy; 2014-2021 <a href="https://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved.
            </footer>

            <aside class="control-sidebar control-sidebar-dark">

            </aside>

        </div>


        <script src="https://adminlte.io/themes/v3/plugins/jquery/jquery.min.js"></script>

        <script src="https://adminlte.io/themes/v3/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>

        <script src="https://adminlte.io/themes/v3/dist/js/adminlte.min.js?v=3.2.0"></script>

        <!-- <script src="https://adminlte.io/themes/v3/dist/js/demo.js"></script> -->
    </body>
    </html>

resources/views/posts/index.blade.php

@extends('layouts.main')
@section('content')
<div class="row">
	<div class="col-md-12">
		<div class="card">
			<div class="card-header">
				<h3 class="card-title">Post List</h3>
			</div>
			@if (session('status'))
			<div class="alert alert-success">
				{{ session('status') }}
			</div>
			@endif
			<div class="card-body">
				<table class="table table-bordered">
					<thead>
						<tr>
							<th>Title</th>
							<th>Description</th>
							<th>Body</th>
							<th>Action</th>
						</tr>
					</thead>
					<tbody>
						@foreach($posts as $post)
						<tr>
							<td>{{ Str::words($post->title,5) }}</td>
							<td>{{ $post->description }}</td>
							<td>
								{{ $post->body }}
							</td>
							<td>
								<div class="btn-group">
									<a href="{{ route('posts.edit',$post) }}" class="btn btn-warning btn-sm"><i class="fa fa-edit"></i></a>
									

									<form method="post" action="{{ route('posts.destroy',$post) }}">
										@method('DELETE')
										@csrf
										<button type="submit" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button>
									</form>
									
								</div>
							</td>
						</tr>
						@endforeach
					</tbody>
				</table>
			</div>

			<div class="card-footer clearfix">
				{{ $posts->links() }}
			</div>
		</div>
	</div>

</div>
@endsection

resources/views/posts/create.blade.php

@extends('layouts.main')
@section('content')
<div class="row">
	<div class="col-md-12">
		<div class="card card-warning">
			<div class="card-header">
				<h3 class="card-title">Create Post</h3>
			</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>
				@endif
				<form method="post" action="{{ route('posts.store') }}">
					<div class="row">
						<div class="col-sm-12">
							<div class="form-group">
								<label>Title</label>
								<input type="text" class="form-control" placeholder="Enter ..." value="{{ old('title') }}" name="title">
							</div>
						</div>
						@csrf
						<div class="col-sm-12">

							<div class="form-group">
								<label>Description</label>
								<textarea class="form-control" rows="3" placeholder="Enter Post Description..." name="description">{{ old('description') }}</textarea>
							</div>
						</div>
						<div class="col-sm-12">
							<div class="form-group">
								<label>Body</label>
								<textarea class="form-control" rows="3" placeholder="Enter Post Body..." name="body">{{ old('body') }}</textarea>
							</div>
						</div>
						<button class="btn btn-primary" type="submit">Submit</button>
					</div>
				</form>
			</div>

		</div>
	</div>

</div>
@endsection

 

resources/views/posts/edit.blade.php

@extends('layouts.main')
@section('content')
<div class="row">
	<div class="col-md-12">
		<div class="card card-warning">
			<div class="card-header">
				<h3 class="card-title">Edit Post : <strong> {{ $post->title }}</strong></h3>
			</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>
				@endif
				<form method="post" action="{{ route('posts.update',$post) }}">
					<div class="row">
						<div class="col-sm-12">

							<div class="form-group">
								<label>Title</label>
								<input type="text" class="form-control" placeholder="Enter ..." value="{{ $post->title }}" name="title">
							</div>
						</div>
						@method('PATCH')
						@csrf
						<div class="col-sm-12">

							<div class="form-group">
								<label>Description</label>
								<textarea class="form-control" rows="3" placeholder="Enter Post Description..." name="description">{{ $post->description }}</textarea>
							</div>
						</div>
						<div class="col-sm-12">
							<div class="form-group">
								<label>Body</label>
								<textarea class="form-control" rows="3" placeholder="Enter Post Body..." name="body">{{ $post->body }}</textarea>
							</div>
						</div>
						<button class="btn btn-primary" type="submit">Submit</button>
					</div>
				</form>
			</div>

		</div>
	</div>

</div>
@endsection

Run Laravel App

All of the steps are completed now, We need to run the laravel project by the following command.

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/posts

post-list-laravel-10

Create Post

create-post-laravel
Edit Post

edit-post-laravel-10

I hope this post is helpful to you.
 

911
Search

Ads