Laravel 8 CRUD with image upload in laravel

Whatsapp

https://www.fundaofwebit.com/post/laravel-8-crud-with-image-upload-tutorial

Complete Laravel 8 IMAGE CRUD application in laravel

Hey Developers,

In this posts, you will be learning about how to make a Complete CRUD application with Image Upload in Laravel 8.

We will be using Bootstrap 5 version to design the user interface like, form, table, etc.

So, Let's get started for Laravel Image CRUD:


Step 1: Install Laravel 8 application by the following command: 

$ composer create-project --prefer-dist laravel/laravel fundaApp "8.0.*"

Step 2: Make a database Configuration in your .env file (like username,password,database) as follows: 

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

Step 3: Lets create a Model and Migration (table) named as Student by following command:

$ php artisan make:model Student -m

After successful execution of above command.

-> Migration: First lets check with the table also known as migration in laravel. So lets go to the path as: database/migrations/2021_05_30_6464_create_students_table.php . open the file and add the below given fields or add your fields as per your requirement:

<?php

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

class CreateStudentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('students'function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('course');
            $table->string('profile_image');
            $table->timestamps();
        });
    }

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

 After adding the fields in migration table called students. Run the below command to migrate it in database as follows:

$ php artisan migrate

-> Model: Second, lets check with model, open the Student.php file in the following path as: app/Models/Student.php and intitalize the table name and its table column fileds as follows:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    use HasFactory;
    protected $table = 'students';
    protected $fillable = [
        'name',
        'email',
        'course',
        'profile_image',
    ];
}

Step 4: Lets create a route for this image CRUD in laravel, so open your web.php file in the following path as: routes/web.php:

<?php

use App\Http\Controllers\StudentController;
use Illuminate\Support\Facades\Route;


Route::get('students', [StudentController::class'index']);
Route::get('add-student', [StudentController::class'create']);
Route::post('add-student', [StudentController::class'store']);
Route::get('edit-student/{id}', [StudentController::class'edit']);
Route::put('update-student/{id}', [StudentController::class'update']);
Route::delete('delete-student/{id}', [StudentController::class'destroy']);

Step 5: Create a controller named StudentController.

in this controller we will be writing all the logics about this IMAGE CRUD i.e, to view page, to insert the data with image, to fetch the data with image, to edit and update data with image and to delete data with image in laravel. So, Lets create a controller by following command:

$ php artisan make:controller StudentController

after successful execution of above command, open the StudentController on the following path as: app/Http/Controllers/StudentController.php and paste the below code in it.

Note: create a folder in your public directory as: uploads/students
<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class StudentController extends Controller
{
    public function index()
    {
        $student = Student::all();
        return view('student.index'compact('student'));
    }

    public function create()
    {
        return view('student.create');
    }

    public function store(Request $request)
    {
        $student = new Student;
        $student->name = $request->input('name');
        $student->email = $request->input('email');
        $student->course = $request->input('course');
        if($request->hasfile('profile_image'))
        {
            $file = $request->file('profile_image');
            $extention = $file->getClientOriginalExtension();
            $filename = time().'.'.$extention;
            $file->move('uploads/students/'$filename);
            $student->profile_image = $filename;
        }
        $student->save();
        return redirect()->back()->with('status','Student Image Added Successfully');
    }

    public function edit($id)
    {
        $student = Student::find($id);
        return view('student.edit'compact('student'));
    }

    public function update(Request $request$id)
    {
        $student = Student::find($id);
        $student->name = $request->input('name');
        $student->email = $request->input('email');
        $student->course = $request->input('course');

        if($request->hasfile('profile_image'))
        {
            $destination = 'uploads/students/'.$student->profile_image;
            if(File::exists($destination))
            {
                File::delete($destination);
            }
            $file = $request->file('profile_image');
            $extention = $file->getClientOriginalExtension();
            $filename = time().'.'.$extention;
            $file->move('uploads/students/'$filename);
            $student->profile_image = $filename;
        }

        $student->update();
        return redirect()->back()->with('status','Student Image Updated Successfully');
    }

    public function destroy($id)
    {
        $student = Student::find($id);
        $destination = 'uploads/students/'.$student->profile_image;
        if(File::exists($destination))
        {
            File::delete($destination);
        }
        $student->delete();
        return redirect()->back()->with('status','Student Image Deleted Successfully');
    }
}

Step 6: Create a folder called student and then create a blade file named index.blade.php in following path: resources/views/student/index.blade.php and paste the code:

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>Laravel 8 IMAGE CRUD
                        <a href="{{ url('add-student') }}" class="btn btn-primary float-end">Add Student</a>
                    </h4>
                </div>
                <div class="card-body">

                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Course</th>
                                <th>Image</th>
                                <th>Edit</th>
                                <th>Delete</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($student as $item)
                            <tr>
                                <td>{{ $item->id }}</td>
                                <td>{{ $item->name }}</td>
                                <td>{{ $item->email }}</td>
                                <td>{{ $item->course }}</td>
                                <td>
                                    <img src="{{ asset('uploads/students/'.$item->profile_image}}" width="70px" height="70px" alt="Image">
                                </td>
                                <td>
                                    <a href="{{ url('edit-student/'.$item->id}}" class="btn btn-primary btn-sm">Edit</a>
                                </td>
                                <td>
                                    {{-- <a href="{{ url('delete-student/'.$item->id) }}" class="btn btn-danger btn-sm">Delete</a> --}}
                                    <form action="{{ url('delete-student/'.$item->id}}" method="POST">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                    </form>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>

                </div>
            </div>
        </div>
    </div>
</div>

@endsection

Step 7: Create a blade file named create.blade.php in following path: resources/views/student/create.blade.php and paste the code:

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6">

            @if (session('status'))
                <h6 class="alert alert-success">{{ session('status'}}</h6>
            @endif

            <div class="card">
                <div class="card-header">
                    <h4>Add Student with IMAGE
                        <a href="{{ url('students') }}" class="btn btn-danger float-end">BACK</a>
                    </h4>
                </div>
                <div class="card-body">

                    <form action="{{ url('add-student') }}" method="POST" enctype="multipart/form-data">
                        @csrf

                        <div class="form-group mb-3">
                            <label for="">Student Name</label>
                            <input type="text" name="name" class="form-control">
                        </div>
                        <div class="form-group mb-3">
                            <label for="">Student Email</label>
                            <input type="text" name="email" class="form-control">
                        </div>
                        <div class="form-group mb-3">
                            <label for="">Student Course</label>
                            <input type="text" name="course" class="form-control">
                        </div>
                        <div class="form-group mb-3">
                            <label for="">Student Profile Image</label>
                            <input type="file" name="profile_image" class="form-control">
                        </div>
                        <div class="form-group mb-3">
                            <button type="submit" class="btn btn-primary">Save Student</button>
                        </div>

                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

@endsection

Step 8: Create a blade file named edit.blade.php in following path: resources/views/student/edit.blade.php and paste the code:

@extends('layouts.app')

@section('content')

<div class="container">
    <div class="row">
        <div class="col-md-12">

            @if (session('status'))
                <h6 class="alert alert-success">{{ session('status'}}</h6>
            @endif

            <div class="card">
                <div class="card-header">
                    <h4>Edit Student with IMAGE
                        <a href="{{ url('students') }}" class="btn btn-danger float-end">BACK</a>
                    </h4>
                </div>
                <div class="card-body">

                    <form action="{{ url('update-student/'.$student->id}}" method="POST" enctype="multipart/form-data">
                        @csrf
                        @method('PUT')

                        <div class="form-group mb-3">
                            <label for="">Student Name</label>
                            <input type="text" name="name" value="{{$student->name}}" class="form-control">
                        </div>
                        <div class="form-group mb-3">
                            <label for="">Student Email</label>
                            <input type="text" name="email" value="{{$student->email}}" class="form-control">
                        </div>
                        <div class="form-group mb-3">
                            <label for="">Student Course</label>
                            <input type="text" name="course" value="{{$student->course}}" class="form-control">
                        </div>
                        <div class="form-group mb-3">
                            <label for="">Student Profile Image</label>
                            <input type="file" name="profile_image" class="form-control">
                            <img src="{{ asset('uploads/students/'.$student->profile_image}}" width="70px" height="70px" alt="Image">
                        </div>
                        <div class="form-group mb-3">
                            <button type="submit" class="btn btn-primary">Update Student</button>
                        </div>

                    </form>

                </div>
            </div>
        </div>
    </div>
</div>

@endsection

Step 9: Now we are ready to run our crud application example with laravel 8 so run bellow command as follows:

$ php artisan serve

after successfully laravel server devlopment starts: open the following url in your browser as:

http://localhost:8000/students


Thanks for reading...

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT