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

Time:04-18

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 >
    <div >
        <input type="file"  name="gallery_img" id="inputGroupFile01">
        <label  for="inputGroupFile01">Choose file</label>
        
    </div>
</div>
@error('gal_img')
    <span >{{ $message }}</span>
@enderror

<div >
    <div  style="padding-left: 1px;">
        <button type="submit" >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.

CodePudding user response:

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',
    ];
}
  • Related