Skip to content
Advertisement

Uploading image from input field and still getting validation error saying that field is required

Route Code:

Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function(){
    Route::resource('gallery', GalleryController::class);
});

The Form I’m Using to Upload the File:

<form action="{{ route('gallery.store') }}" method="post" enctype="multipart/form-data">
@csrf

<div class="input-group mb-3">
    <div class="custom-file">
        <input type="file" class="custom-file-input" name="gallery_img" id="inputGroupFile01">
        <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
        
    </div>
</div>
@error('gal_img')
    <span class="text-danger">{{ $message }}</span>
@enderror

<div class="input-group-append">
    <div class="col-sm-10" style="padding-left: 1px;">
        <button type="submit" class="btn btn-dark">Save</button>
    </div>
</div>                            

Controller Code:

    public function store(GalleryRequests $request)
{
    $gal_img = $request->file('gallery_img');
    $gal_file = date('YmdHi').$gal_img->getClientOriginalName();
    $gal_img->move(public_path('upload/gallery'), $gal_file);
    $save_path = 'upload/gallery/'.$gal_file;

    Gallery::insert([
        'gal_img' => $save_path
    ]);

    $notification = array(
        'message' => 'Slider Inserted Successfully',
        'alert-type' => 'success'
    );

    return redirect()->back()->with($notification);
}

Request file validation:

 public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'gal_img' => 'required'
    ];
}

public function messages(){
    return [
        'gal_img.required' => 'Please Select an Image First',
    ];
}

The error I get when trying to save after selecting an Image: enter image description here

Trying to figure out what I’ve done wrong for hours and am so frustrated right now, please help me to resolve this issue. Thanks in advance.

Advertisement

Answer

Field in form is named gallery_img so that name has to be checked:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'gallery_img' => 'required'
    ];
}

public function messages()
{
    return [
        'gallery_img.required' => 'Please Select an Image First',
    ];
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement