Laravel 12 E-Commerce: Admin Create New Brand
Hi everyone, welcome back to the Laravel E-Commerce Project Tutorial. In this video, we will learn how to implement the functionality to add a new brand to the admin panel.
1. Create Controller Function and View
Create View Function (`AdminController.php`)
In the `AdminController`, create a function to render the "add brand" view:
public function add_brand()
{
return view("admin.brand-add");
}
Define Route for View (`web.php`)
Create the GET route for accessing the new brand form:
Route::get("/admin/brand/add",[AdminController::class,"add_brand"])->name("admin.brand.add’);
Create and Setup View (`brand-add.blade.php`)
Create the view file at `resources/views/admin/brand-add.blade.php` and extend the admin layout:
<x-admin-layout>
</x-admin-layout>
Inside the view, integrate the content from the `add-brand.html` template file (specifically the `main-content-inner` section) and ensure the Admin Dashboard link is correctly routed:
{{route("admin.index’)}}
2. Add "Add New Brand" Link to Brands Page
Open the `brands.blade.php` view file and add a button/link to navigate to the new brand creation page:
<a href="{{route("admin.brand.add")}}" class="btn btn-sm btn-outline-primary float-end" style="display: flex; align-items: center; vertical-align: middle;">
<i class="material-icons" style="margin-right: 4px;">add</i>
Add New
</a>
After implementing this, you should be able to click "Add New" on the Brands page and see the form.
3. Implement Brand Store Logic (AdminController)
Store Function (`add_brand_store`)
In `AdminController.php`, create a POST function to handle form submission, including validation, slug generation, image processing, and saving to the database. This logic assumes a helper function `GenerateBrandThumbailImage` exists for image handling.
public function add_brand_store(Request $request)
{
$request->validate([
"name" => "required",
"slug" => "required|unique:brands,slug",
"image" => "mimes:png,jpg,jpeg|max:2048"
]);
$brand = new Brand();
$brand->name = $request->name;
$brand->slug = Str::slug($request->name);
$image = $request->file("image");
$file_extention = $request->file("image")->extension();
$file_name = Carbon::now()->timestamp . "." . $file_extention;
$this->GenerateBrandThumbailImage($image, $file_name);
$brand->image = $file_name;
$brand->save();
return redirect()->route("admin.brands");
}
Define Route for Store (`web.php`)
Define the POST route that the form will submit to:
Route::post("/admin/brand/store",[AdminController::class,"add_brand_store"])->name("admin.brand.store’);
4. Update Form in View (`brand-add.blade.php`)
Form Structure and Validation
Update the form element in `brand-add.blade.php` with the correct action, method, `enctype` for file upload, CSRF token, and logic to display validation errors:
<div class="card-body">
<form action="{{route("admin.brand.store")}}" method="POST" enctype="multipart/form-data" data-parsley-validate>
@csrf
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label" for="Name">Name</label>
<input type="text" class="form-control" name="name" placeholder="" required data-parsley-trigger="change">
@error("name") <span class="alert alert-danger text-center">{{$message}}</span> @enderror
</div>
<div class="col-md-6">
<label class="form-label" for="slug">slug</label>
<input type="text" class="form-control" name="slug" placeholder="" required data-parsley-trigger="change">
@error("slug") <span class="alert alert-danger text-center">{{$message}}</span> @enderror
</div>
</div>
<div class="mb-3">
<label class="form-label" for="image">Image</label>
<input type="file" class="form-control" id="myImage" name="image" accept="image/*" required data-parsley-trigger="change">
@error("image") <span class="alert alert-danger text-center">{{$message}}</span> @enderror
</div>
<div class="mb-3">
<img id="image-preview" src="" alt="Image Preview" style="display: none; max-width: 120px; height: auto;">
</div>
<div class="mb-3">
<button type="button" class="btn btn-danger btn-sm" id="remove-image" style="display: none;">Remove Image</button>
<p id="message" style="color: green;"></p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
JavaScript for Image Preview and Slug Generation
Add the following JavaScript to handle image preview, removal, and automatic slug generation from the brand name using a custom `StringToSlug` function.
@push("scripts")
<script>
$(function() {
$("#myImage").on("change", function(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
$("#image-preview").attr("src", e.target.result).show();
$("#remove-image").show();
$("#message").text("Image selected. You can remove it if needed.");
}
if (file) {
reader.readAsDataURL(file);
} else {
$("#image-preview").attr("src", "").hide();
$("#remove-image").hide();
$("#message").text("");
}
});
$("#remove-image").on("click", function() {
$("#image-preview").attr("src", "").hide();
$("#myImage").val("");
$(this).hide();
$("#message").text("Image removed.");
});
$("input[name="name"]").on("change", function() {
$("input[name="slug"]").val(StringToSlug($(this).val()));
});
});
function StringToSlug(Text)
{
return Text.trim().toLowerCase()
.replace(/([W_])+/g, "")
.replace(/ +/g,"-");
}
</script>
@endpush
5. Testing
After implementing all changes, navigate to the Admin page, click on the Add New Brand link, fill in the form (name, image), and click Submit. The brand should be successfully added and you should be redirected back to the main Brands page.
This completes the process for creating new brands in the admin panel.
