Laravel CRUD with image attribute for beginners

I’ll demonstrate a laravel crud operation with the image attribute. This will help you understand the laravel framework, and how to use it to handle an image or a file with laravel.

Let’s make a laravel CRUD application by following a few simple steps.

First, you need to install a few things

  • Node js
  • Xampp
  • Composer

Step 1, Install laravel

In order to build up a new Laravel application, choose a folder and run the following command in your terminal or command prompt first:

composer create-project laravel/laravel crud

Step 2, Database configuration

For our CRUD application, we will create the database settings in the second step, including the database name, username, and password. So let’s open the.env file and enter all the information as follows:

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

Step 3, Create Model

We’re going to make crud for the product model. Therefore, we must build a model, controller, and migration of the “Product” model using the PHP artisan command. To start, run the line below:

php artisan make:model People -mcr

This will create a model, migration, and a controller

Step 4, setting up the migration

Now we need to set up our migration file to create a product table

<?php

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

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('persons', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image');
            $table->timestamps();
        });
    }

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

Now you can migrate your table using the following command

php artisan migrate:fresh

Step 5, Set up a model

Once you’re done with migration it’s time to set up your model open your Product.php from the model folder and add these lines

<?php

namespace App\Models;

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

class People extends Model
{
    use HasFactory;

    protected $fillable = ['name','image'];
}

Step 6, Setup your functions in the controller 

After your model setup, you need to create CRUD functions in your controller to perform your CRUD operations

<?php

namespace App\Http\Controllers;

use App\Models\Person;
use Illuminate\Http\Request;

class PersonController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $person = Person::all();
        $i = 1;
        return view('index',compact('person','i'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'name'=>'required',
            'image'=>'required',
        ]);

        $person = new  Person();
        $image = $request->file('image');
        $image_new_name = time(). $image->getClientOriginalName();
        $image->move('images/personImage/',$image_new_name);
        $person->name = $request->name;
        $person->image ='images/personImage/'.$image_new_name;
        $person->save();
         
        return  redirect()->back();
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Person  $person
     * @return \Illuminate\Http\Response
     */
    public function show(Person $person)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Person  $person
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $person = Person::find($id);
        return view('edit',compact('person'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Person  $person
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name'=>'required',
            'image'=>'required',
        ]);

        $person = Person::find($id);
        $image = $request->file('image');
        $image_new_name = time().$image->getClientOriginalName();
        $image->move('images/personImage/',$image_new_name);
        $person->name = $request->name;
        $person->image ='images/personImage/'.$image_new_name;
        $person->update();

        return redirect()->route('index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Person  $person
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $person = Person::find($id);
        $person->delete();
        return redirect()->back();
    }
}

Step  7, Setup routes

After you’re done with functions now you need to set up your routes

<?php

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

/*
|--------------------------------------------------------------------------
| 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('/',[PersonController::class,'index'])->name('index');
Route::post('/',[PersonController::class,'store'])->name('store');
Route::get('/edit/{id}',[PersonController::class,'edit'])->name('edit');
Route::post('/update/{id}',[PersonController::class,'update'])->name('update');
Route::get('/delete/{id}',[PersonController::class,'destroy'])->name('delete');


Step  8, Setup views

After setting up your routes create a two-blade file inside your view folder 

Index.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CRUD with image</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>

<body>

    <div class="container mt-4">
        <form action="{{route('store')}}" method="post" enctype="multipart/form-data">
            {{csrf_field()}}
            <div class="mb-3">
                <label for="exampleFormControlInput1" class="form-label">name</label>
                <input type="text" name="name" class="form-control" id="exampleFormControlInput1">
            </div>
            <div class="mb-3">
                <label for="exampleFormControlTextarea1" class="form-label">Image</label>
                <input type="file" name="image" placeholder="image">
            </div>
            <input type="submit"  value="Submit" class="btn btn-primary">
        </form>
    </div>

    <div class="container">
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col"> Name</th>
                    <th scope="col" width="50%"> Image</th>
                    <th scope="col">Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach($person as $item)
                <tr>
                    <th scope="row">{{$i}}</th>
                    <td>{{$item->name}}</td>
                    <td><img src="{{$item->image}}" width="20%" alt=""></td>
                    <td><a href="{{route('edit',$item->id)}}" class="btn btn-primary">Edit</a><a href="{{route('delete',$item->id)}}" class="btn btn-danger ms-2">Delete</a></td>
                </tr>
                <?php $i++ ?>
                @endforeach
            </tbody>
        </table>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
</body>

</html>

edit.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CRUD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
</head>

<body>

    <div class="container mt-4">
        <form action="{{route('update',$person->id)}}" method="post" enctype="multipart/form-data">
            {{csrf_field()}}
            <div class="mb-3">
                <label for="exampleFormControlInput1" class="form-label">name</label>
                <input type="text" name="name" value="{{$person->name}}" class="form-control" id="exampleFormControlInput1">
            </div>
            <img src="../{{$person->image}}" width="10%" class="mb-4" alt="">
            <div class="mb-3">
                <label for="exampleFormControlTextarea1" class="form-label">Image</label>
                <input type="file" name="image" placeholder="image">
            </div>
            <input type="submit"  value="Submit" class="btn btn-primary">
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
</body>

</html>

Step 9 Result

You’ll find this end result if you do it correctly

Index page view

Edit view

Rishikesh Karki
Rishikesh Karki
Articles: 5

6 Comments

  1. Excellent goods from you, man. I have understand your stuff previous to and you’re just too wonderful. I really like what you have acquired here, really like what you’re saying and the way in which you say it. You make it entertaining and you still take care of to keep it sensible. I cant wait to read much more from you. This is really a terrific website.

Leave a Reply

Your email address will not be published. Required fields are marked *