Handle file upload in Laravel 5

Handling file upload in Laravel 5+ is pretty much easier than you thought.

In order to get file upload entity, there needs to inject Request object to get an UploadedFile instance.

Following is a very basic file upload handler,

public function upload(Request $request)
{
if(!$request->hasFile(‘data’)) {
return response()->json([‘upload_file_not_found’], 400);
}
  $file = $request->file(‘data’);
  if(!$file->isValid()) {
return response()->json([‘invalid_file_upload’], 400);
}
  $path = public_path() . ‘/uploads/’;
$file->move($path, $file->getClientOriginalName() );
  return response()->json(compact(‘path’));
}
  • To check whether a request containing an upload file, use Request::hasFile().
  • To get an upload file, which will be an UploadFile instance eventually, use Request::file().
  • To check whether an upload file is valid, use Request::isValid().
  • After owning an UploadFile instance, you can move files to a directory, ideally you will move files to the public directory, where they are accessible via web server requests, or anything else you can think of.

Have fun :)

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.