Thursday, March 16, 2017

How mime type validation works in Laravel

I already tried different ways on how to validate the files but it still not working. The validation rule that I tried are the ff: mimes & mimetypes. I want to validation the files to be uploaded either single file or multiple. Here is code that I want to validate the file

 $this->validate($request, [
        'body' => 'required|max:120',
        'file' => 'mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    $user = Auth::user();

    $post = new Post();
    $post->body = $request['body'];
    $post->user_id = $user->id;
    $files = $request['file'];
    $post->save();

    if ($request->hasFile('file')) :
        foreach ($files as $file):
            $filename = time() . '.' . $file->getClientOriginalExtension();
            $originalname = $file->getClientOriginalName();
            $location = public_path('attachments/');
            $file->move($location, $file->getClientOriginalName());
            $post_file = new File();
            $post_file->file_name = $filename;
            $post_file->previous_file_name = $originalname;
            $post_file->user_id = $user->id;
            $post->files()->save($post_file);
            $post_file->save();
        endforeach;
    endif;



via Kenneth

Advertisement