Harshit Singh
Harshit Singh

Reputation: 35

Laravel Video, Audio and image upload

This is my image upload method of PostsController

public function store(Request $request, User $user, Image $image)
{
    $this->validate($request, [
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        'body' => 'required'
    ]);


    if( $request->hasFile('image') ) {
        $image = $request->file('image');
        $filename = time() . '.' . $image->getClientOriginalExtension();

        Image::make($image)->save( public_path('uploads/images/' . $filename ) );
    } 

    $image = $filename;

    auth()->user()->publish(
        new Post(['body' => request('body'), 'image' => $image, 'user_id' => auth()->id()])
    );

    return redirect('/');
}

I want one method to upload image, video and audio as well with one input that user can upload image or video or audio How can i do all these things in one controller?

Upvotes: 0

Views: 6911

Answers (2)

Mayur Panchal
Mayur Panchal

Reputation: 655

If you are using form requests, try with below code

  public function rules() {
    $rules = [
        'some_field' => 'required',
    ];

    //  if fileType is audio
    if ($this->input('fileType') == 'audio') {
        $rules['file'] = 'mimes:mp3,mp4';
    }

    //if fileType is video
    if ($this->input('fileType') == 'video') {
         $rules['file'] = 'mimes:mp4,3gp';

    }
    return $rules;
}

field names and validation rules change as per your requirement.

Upvotes: 0

muya.dev
muya.dev

Reputation: 977

First determine the whether the file is a video, audio or image. Then decide how you validate. Hope this will help.

if( $request->hasFile('file') ) {
		$file = $request->file('file');
		$imagemimes = ['image/png']; //Add more mimes that you want to support
		$videomimes = ['video/mp4']; //Add more mimes that you want to support
		$audiomimes = ['audio/mpeg']; //Add more mimes that you want to support

		if(in_array($file->getMimeType() ,$imagemimes)) {
			$filevalidate = 'required|mimes:jpeg|max:2048';
		}
		//Validate video
		if (in_array($file->getMimeType() ,$videomimes)) {
			$filevalidate = 'required|mimes:mp4';
		}
		//validate audio
		if (in_array($file->getMimeType() ,$audiomimes)) {
			$filevalidate = 'required|mimes:mpeng';
		}		
    }
    $this->validate($request, [
        'file' => $filevalidate,
        'body' => 'required'
    ]);

Upvotes: 1

Related Questions