CRUD Operation with File / Image Upload Tutorial in Laravel 10 step-by-step
In this post, you will learn how to upload images with other field data in Laravel. So guys let's get started.
Step 1: Create Laravel Application and Connect Database. I hope you have already done with this process.
Step 2: Create Migration named 'categories' as follows:
php artisan make:migration create_categories_table
After successfully creating the migration file paste the below code.
<?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('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('description');
$table->string('image')->nullable();
$table->boolean('is_active')->default(1);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('categories');
}
};
Step 3: Let's migrate the file into database with the below artisan command:
php artisan migrate
Step 4: Create a Model named Category using the artisan command:
php artisan make:model Category
after successfully creating the model, update the $table & $fillable property in eloquent model as given below:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $table = 'categories';
protected $fillable = [
'name',
'description',
'image',
'is_active'
];
}
Step 5: Create a Controller named CategoryController using the below artisan command:
php artisan make:controller CategoryController
after successfully creating the above controller "app /Http /Controllers /CategoryController.php" , paste the below code:
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::get();
return view('category.index', compact('categories'));
}
public function create()
{
return view('category.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required|max:255|string',
'description' => 'required|max:255|string',
'image' => 'nullable|mimes:png,jpg,jpeg,webp',
'is_active' => 'sometimes'
]);
$filename = NULL;
$path = NULL;
if($request->has('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$path = 'uploads/category/';
$file->move($path, $filename);
}
Category::create([
'name' => $request->name,
'description' => $request->description,
'image' => $path.$filename,
'is_active' => $request->is_active == true ? 1:0,
]);
return redirect('categories/create')->with('status','Category Created');
}
public function edit(int $id)
{
$category = Category::findOrFail($id);
return view('category.edit', compact('category'));
}
public function update(Request $request, int $id)
{
$request->validate([
'name' => 'required|max:255|string',
'description' => 'required|max:255|string',
'image' => 'nullable|mimes:png,jpg,jpeg,webp',
'is_active' => 'sometimes'
]);
$category = Category::findOrFail($id);
if($request->has('image')){
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = time().'.'.$extension;
$path = 'uploads/category/';
$file->move($path, $filename);
if(File::exists($category->image)){
File::delete($category->image);
}
}
$category->update([
'name' => $request->name,
'description' => $request->description,
'image' => $path.$filename,
'is_active' => $request->is_active == true ? 1:0,
]);
return redirect()->back()->with('status','Category Update');
}
public function destroy(int $id)
{
$category = Category::findOrFail($id);
if(File::exists($category->image)){
File::delete($category->image);
}
$category->delete();
return redirect()->back()->with('status','Category Deleted');
}
}
Step 6: Create a Route in the following path: routes/web.php file
Route::controller(App\Http\Controllers\CategoryController::class)->group(function () {
Route::get('categories', 'index');
Route::get('categories/create', 'create');
Route::post('categories/create', 'store');
Route::get('categories/{id}/edit', 'edit');
Route::put('categories/{id}/edit', 'update');
Route::get('categories/{id}/delete', 'destroy');
});
Step 7: Create a blade files for Category
Create a folder named category in the following path: "resources / views / category / your_blade_files" and then create the listed below files as follows:
1. create.blade.php
2. edit.blade.php
3. index.blade.php
I am using Bootstrap 5.3 & above to design the UI
1. Open the create.blade.php file from the path resources/ views/ category/ create.blade.php and paste the below code by extending your layout
<div class="container mt-5">
<div class="row">
<div class="col-md-12">
@if (session('status'))
<div class="alert alert-success">{{session('status')}}</div>
@endif
<div class="card">
<div class="card-header">
<h4>Add Categories
<a href="{{ url('categories') }}" class="btn btn-primary float-end">Back</a>
</h4>
</div>
<div class="card-body">
<form action="{{ url('categories/create') }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="mb-3">
<label>Name</label>
<input type="text" name="name" class="form-control" value="{{ old('name') }}" />
@error('name') <span class="text-danger">{{ $message }}</span> @enderror
</div>
<div class="mb-3">
<label>Description</label>
<textarea name="description" class="form-control" rows="3">{{ old('description') }}</textarea>
@error('description') <span class="text-danger">{{ $message }}</span> @enderror
</div>
<div class="mb-3">
<label>Is Active</label>
<input type="checkbox" name="is_active" {{ old('is_active') == true ? checked:'' }} />
@error('is_active') <span class="text-danger">{{ $message }}</span> @enderror
</div>
<div class="mb-3">
<label>Upload File/Image</label>
<input type="file" name="image" class="form-control" />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
2. Open the edit.blade.php file from the path resources/ views/ category/ edit.blade.php and paste the below code by extending your layout
<div class="container mt-5">
<div class="row">
<div class="col-md-12">
@if (session('status'))
<div class="alert alert-success">{{session('status')}}</div>
@endif
<div class="card">
<div class="card-header">
<h4>Edit Categories
<a href="{{ url('categories') }}" class="btn btn-primary float-end">Back</a>
</h4>
</div>
<div class="card-body">
<form action="{{ url('categories/'.$category->id.'/edit') }}" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="mb-3">
<label>Name</label>
<input type="text" name="name" class="form-control" value="{{ $category->name }}" />
@error('name') <span class="text-danger">{{ $message }}</span> @enderror
</div>
<div class="mb-3">
<label>Description</label>
<textarea name="description" class="form-control" rows="3">{{ $category->description }}</textarea>
@error('description') <span class="text-danger">{{ $message }}</span> @enderror
</div>
<div class="mb-3">
<label>Is Active</label>
<input type="checkbox" name="is_active" {{ $category->is_active == true ? 'checked':'' }} />
@error('is_active') <span class="text-danger">{{ $message }}</span> @enderror
</div>
<div class="mb-3">
<label>Upload File/Image</label>
<input type="file" name="image" class="form-control" />
</div>
<div class="mb-3">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
3. Open the index.blade.php file from the path resources/ views/ category/ index.blade.php and paste the below code by extending your layout
<div class="container mt-5">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h4>Categories
<a href="{{ url('categories/create') }}" class="btn btn-primary float-end">Add Category</a>
</h4>
</div>
<div class="card-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Image</th>
<th>Is Active</th>
<th>Action</th>
</tr>
</thead>
<tbody>
@foreach ($categories as $item)
<tr>
<td>{{$item->id}}</td>
<td>{{$item->name}}</td>
<td>{{$item->description}}</td>
<td>
<img src="{{ asset($item->image) }}" style="width: 70px; height:70px;" alt="Img" />
</td>
<td>
@if ($item->is_active)
Active
@else
In-Active
@endif
</td>
<td>
<a href="{{ url('categories/'.$item->id.'/edit') }}" class="btn btn-success mx-2">Edit</a>
<a
href="{{ url('categories/'.$item->id.'/delete') }}"
class="btn btn-danger mx-1"
onclick="return confirm('Are you sure ?')"
>
Delete
</a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Finally let's serve the application using the artisan command:
php artisan serve
I hope this helps you. Thanks for reading.