CRUD Application with Image Upload Using Laravel 8
Share this post:
In this post, I'm going to show you how to build a CRUD (Create, Read, Update, Delete) Application with Image upload and pagination using Bootstrap 5 and Laravel 8. In this tutorial, you'll see how to create a basic CRUD application in which you will learn how to insert records with image upload, how to display all the records with image and pagination, how to edit and update the record with image and how to delete a record.
You just need to follow a few steps, and you will get a CRUD Application with Image upload using controller, model, route, bootstrap 5 and blade syntax.
Now just follow all the steps very carefully one by one. don't worry I'll share all the codes here so just copy and paste them into your application.
Step 1: Installing Laravel 8
First, you have to install a fresh Laravel 8 application using composer, for this, you just have to open your terminal and run the below command.
composer create-project laravel/laravel crud-app
Step 2: Database Configuration
Now in this step, you have to write your database credentials into the .env file, but first, open your phpmyadmin and create a new database with the name βcrud_appβ. Now just see the below codes, if you have set any username or password other than mine then just write your own credentials.
In this step, we'll create our Model, migration and controller using a single command.
php artisan make:model Post -mc --resource
-m flag is used to create a migration; c flag is used to create a controller and --resource flag is used for creating a controller with some basic CRUD scaffolding methods.
Step 4: Defining Schema
Now in this step, we'll define our βpostsβ table schema so for this just open database/migrations/create_posts_table.php and just use the below codes.
<?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->string('category');
$table->longText('content');
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('posts');
}
}
Now you have to run this migration by the following command:
php artisan migrate
Step 5: Creating Routes
Now in this step, we'll create routes for our CRUD application. We'll create a resource route in which all the routes will be present. Just use the below codes.
Now to see all the routes you have to run a command:
php artisan route:list
Routes List
Step 6: Working in Model
Now in this step, we'll write some codes in the Post model. So, for this just open the app/Models/Post.php file and put the below codes.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
use HasFactory;
protected $fillable = ['title', 'category', 'content', 'image'];
}
Step 7: Working in Controller
Now, this is the most important step, in this, we'll write all the application logic. So, for this just open the app/Http/Controllers/PostController.php file and define each method like the below codes you can copy and paste the below codes.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class PostController extends Controller {
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index() {
$posts = Post::orderBy('id', 'desc')->paginate(3);
return view('post.index', ['posts' => $posts]);
}
/**
* Show the form for creating a new resource.
*
* @return IlluminateHttpResponse
*/
public function create() {
return view('post.create');
}
/**
* Store a newly created resource in storage.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function store(Request $request) {
$request->validate([
'title' => 'required',
'category' => 'required',
'content' => 'required|min:50',
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time() . '.' . $request->file->extension();
// $request->image->move(public_path('images'), $imageName);
$request->file->storeAs('public/images', $imageName);
$postData = ['title' => $request->title, 'category' => $request->category, 'content' => $request->content, 'image' => $imageName];
Post::create($postData);
return redirect('/post')->with(['message' => 'Post added successfully!', 'status' => 'success']);
}
/**
* Display the specified resource.
*
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function show(Post $post) {
return view('post.show', ['post' => $post]);
}
/**
* Show the form for editing the specified resource.
*
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function edit(Post $post) {
return view('post.edit', ['post' => $post]);
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function update(Request $request, Post $post) {
$imageName = '';
if ($request->hasFile('file')) {
$imageName = time() . '.' . $request->file->extension();
$request->file->storeAs('public/images', $imageName);
if ($post->image) {
Storage::delete('public/images/' . $post->image);
}
} else {
$imageName = $post->image;
}
$postData = ['title' => $request->title, 'category' => $request->category, 'content' => $request->content, 'image' => $imageName];
$post->update($postData);
return redirect('/post')->with(['message' => 'Post updated successfully!', 'status' => 'success']);
}
/**
* Remove the specified resource from storage.
*
* @param AppModelsPost $post
* @return IlluminateHttpResponse
*/
public function destroy(Post $post) {
Storage::delete('public/images/' . $post->image);
$post->delete();
return redirect('/post')->with(['message' => 'Post deleted successfully!', 'status' => 'info']);
}
}
We have stored all the images in the storage directory so to access those images from the public directory we have to run a simple command:
php artisan storage:link
We are storing all the images in the storage/images directory.
Step 8: Working in Views
In this step, we'll create our views using a blade templating engine. Here we'll use the Bootstrap 5 framework for designing this application. So, let's first create a layout file that will be extended by the child views.
Create a new folder in the resources/views directory with name layout and inside the layout, the directory creates a new file with name app.blade.php and just copy the below codes and paste it into your file.
Now in order to fix the pagination issue, you have to add one line code to the app/Providers/AppServiceProvider.php file. Just use the below codes inside the boot() method.
Paginator::useBootstrap();
Step 9: Serve The Application
Now our application is ready to be served. You just need to run a command to run your CRUD Application. Just use the below command in your terminal:
php artisan serve
Now open your browser and put http://127.0.0.1:8000/post to the address bar and hit enter to use your application.
Share this post:
Sahil Kumar
Full Stack Web Developer
Hello! I'm a part-time blogger & YouTuber living in India. This is my personal blog where I write Web Design & Development tutorial posts!
You are a very good developer Sir Sahil i am new to Laravel and im from malawi i have learned few things from you particulary on pagination and how i can intergrate my laravel application with Bootstrap, sweet alerts , Ajax etc. i can confidently say i have gained an exceptional skills and a starting point of my journey in Laravel Development
SUBMIT GUEST POST π
Ready to contribute? Head to the article dashboard to publish your own insightful articles and share them with our audience!