Laravel 8 Tutorial - File Upload
In this tutorial, we are going to learn about file upload in Laravel 8.
So, let's see how we can upload a file in Laravel 8. First of all, let's create a new controller. Switch to the command prompt and run the command:
php artisan make:controller UploadController
Now, switch to the project and open the UploadController. Here, let's create a function:
public function uploadForm()
{
return view('upload');
}
Now, create the upload view. Go to the views folder and create a new file, upload.blade.php.
Next, create a route for this. Go to the web.php file and create the route:
Route::get('/upload','FileController@uploadForm');
Now, open the upload.blade.php file and write the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Upload</title>
{{-- Add here bootstrap css cdn --}}
</head>
<body>
<section style="padding-top:30px">
<div class="container">
<div class="row">
<div class="col-md-8 offset-md-2 text-center">
<form method="POST" action="{{route('upload')}}" enctype="multipart/form-data">
@csrf
<div class="form-group">
<label for="file">Choose</label>
<input type="file" class="form-control-file" name="file" id="file">
</div>
<button type="submit" class="btn btn-success" name="submit">Submit</button>
</form>
</div>
</div>
</div>
</section>
</body>
</html>
Save this and let's check the form. Switch to the browser and go to the URL /upload. You can see the form here.
Now, go to the UploadController and create another function:
public function uploadFile(Request $req)
{
$request->file->store('public');
return "File has been uploaded successfully!";
}
Create a route for this function. Go to the web.php file and create a route:
Route::post('/upload','FileController@uploadFile')->name('upload');
Save the file and let's check. Refresh the page, select a file, and click on submit. You can see the message "File has been uploaded successfully."
Now, let's find the uploaded file. Go to the project directory, open the storage folder, then app, and public. You can see the file here.
Try uploading another file. Choose another file and click on submit. The file is uploaded, and in the storage folder, you can see the new file.
So, in this way, you can upload files in Laravel 8.