mardi 21 janvier 2020

Unable to store uploaded image using PHP and Laravel

I am learning Laravel and attempting to create a webpage to upload Picture albums. I have read up on the laravel documentation on verification and each field is being verified. However, upon clicking submit, the image does not post to the store method.

The route is set in web.php

Route::get('/albums/create', 'AlbumsController@create')->name("album-create");
Route::post('/albums/store', 'AlbumsController@store')->name("album-store");

The form code is shown below:

<div class="container">

  <h2> Create New Album </h2>

    <form method="post" action="" enctype="multipart/form-data">
      <input type="hidden" name="_token" value="">

        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" name="name" id="name" placeholder="Enter Name: ">
        </div>
        <div class="form-group">
            <label for="name">Description</label>
            <input type="text" class="form-control" name="description" id="description"  placeholder="Enter description">
        </div>
        <div class="form-group">
            <label for="name">Cover Image</label>
            <input type="file" class="form-control" name="cover_image" id="cover-image" placeholder="cover-image">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
      </form>

and finally we have the controller function below:

public function store(Request $request) {
  $this->validate($request, [
    'name' => 'required',
    'description' => 'required',
    'cover-image' => 'required'
  ]);

  $filenameWithExtension = $request->file('cover-image')->getClientOriginalName();

      $filename = pathinfo($filenameWithExtension, PATHINFO_FILENAME);

      $extension = $request->file('cover-image')->getClientOriginalExtension();
// time stamping the images uplaoded
      $filenameToStore = $filename . '_' . time() . '.' . $extension;

// saving the file to the disk (can be found in 'storage/app/public/album_covers..')
      $request->file('cover-image')->storeAs('public/album_covers', $filenameToStore);

  $album = new Album();
  $album->name = $request->input('name');
  $album->description = $request->input('description');
  $album->cover_image = $filenameToStore;
  $album->save();

When I click submit on the form after filling the fields, I still receive the error "Cover-image" is required. enter image description here



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire