Image upload

This feature allows users to securely upload images.

The upload form uses the POST method with multipart/form-data encoding and includes a CSRF token for protection.

Once a file is selected and "save" is clicked, it is sent to the designated endpoint, stored, and recorded in the database..

Form:
<form action="/upload" method="post" enctype="multipart/form-data">
  @csrf
  <label>Upload Picture</label><br>
  <input type="file" name="picture" /><br>
  <input type="submit" value="save" />
</form>

Controller Method for Uploading the Image:

1. Validate the File:

Ensure the uploaded file is provided and is of the correct MIME types (jpg, png).

2. Store the File:

Hash the file name for uniqueness and save it in the storage/app/public/images directory.

3. Insert into Database:

Add a record of the file into the pictures table.

public function upload(Request $request)
{
        // 1) Validate the uploaded file
validate([
        'picture' => 'required|mimes:jpg,png'
     ]);
      // 2) Hash the picture name
    $pictureName = $request->file('picture')->hashName();
      // 3) Store the file in the "public/images" directory .
    $request->file('picture')->store('public/images');
     // 4) Insert the picture into the database
    DB::table('pictures')->insert([
    'name' => 'Picture1',
    'path' => $pictureName
   ]);
    // 5) Redirect the user
    return redirect('/');
}

Displaying the Uploaded Images:

Retrieve the images from the database and display them.

Use the asset helper to load images from the storage directory.

public function index()
{
  $pictures = DB::table('pictures')->get();
    return view('welcome', ['pictures' => $pictures]);
}
<div>
    @foreach($pictures as $pic)
          <img src="{{ asset('storage/images/' . $pic->path) }}" alt="{{ $pic->name }}"><br>
          <a href="delete/{{ $pic->id }}">DELETE</a><br><br>
    @endforeach
</div>

Note: Run php artisan storage:link to create a symbolic link from the storage directory to the public folder,

ensuring the files are accessible via the browser.


Deleting an Image:

Remove both the file from storage and its record from the database.

public function delete($id)
{
    $picture = DB::table('pictures')->find($id);
    Storage::delete('public/images/' . $picture->path);
    DB::table('pictures')->delete($id);
    return redirect('/');
}