KB_Shayan
KB_Shayan

Reputation: 652

Laravel: Image validation on multiple images does not work

A registered user can create a post and with that post, a user can upload multiple pictures. However the issue I am having is that it fails to validate the file upload correctly. I used:

mimes:jpg,jpeg,png

However, when I upload images that are those types it says they are not. Before implementing multiple image upload I had 1 image upload in place and it was fine, but when I made it multiple images it broke it.

Here is my postController.php method for creating a post:

public function postCreatePost(Request $request){
   //validates each field 
    $this->validate($request, [
        'title' => 'required|max:100',
        'type' => 'required',
        'subtype' => 'required|max:100',
        'date' => 'required|date',
        'venue' => 'required|max:100',
        'body' => 'required',
        'cover_image' => 'required|mimes:jpeg,jpg,png'
    ]);

    //adds each field sent in the request to the relevant post table column
    $post = new Post(); 
    $post->title = $request['title'];
    $post->type = $request['type'];
    $post->subtype = $request['subtype'];
    $post->date = $request['date'];
    $post->venue = $request['venue'];
    $post->body = $request['body'];



    $message = 'There was an error';
    if($request->user()->posts($post)->save($post)){ //submits record to post table and if succesful it will enter loop

        //creats image name and stores it in images table and stores the image in the cover_images directory
        if($request->hasFile('cover_image')){
            foreach($request->file('cover_image') as $file){
                $filenameWithExt = $file->getClientOriginalName();
                $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
                $extension = $file->getClientOriginalExtension();
                $fileNameToStore = $filename . '_' . time() . '.' . $extension; 
                $path = $file->storeAs('public/cover_images', $fileNameToStore);
                $image = new Image();
                $image->cover_image = $fileNameToStore;
                $image->post_id = $post->id;
                $image->save();
            }
        }

        $message = 'post successfully created';
    }

    return redirect()->route('dashboard')->with(['message' => $message]); // redirects user back to the dashboard
}

Upvotes: 2

Views: 2244

Answers (1)

Serge
Serge

Reputation: 2187

Try this...

'cover_image.*' => 'required|mimes:jpeg,jpg,png'

Or this ...

'cover_image.*.file' => 'required|mimes:jpeg,jpg,png'

Upvotes: 5

Related Questions