Upload files to Laravel app
Almost any web app uses one kind or another of file uploading utility and Laravel as one of the most modern frameworks for programming websites is no exception. Yet, I think that the official documentation (which is remarkable in almost any aspect) is somewhat lacking in explaining this. The short code in this page demonstates how I build file uploading utilities with Laravel. I hope it can help you to.
1. The routes
According to Laravel's CRUD documentation.
routes/web.php
<?php
Route::get('files/create','FilesController@create');
Route::post('files','FilesController@store');
2. The controller
Read the Laravel documentation to learn about other validation rules.
app/Http/Controllers/FilesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class FilesController extends Controller
{
protected $docRoot = '';
protected $publicDir = '/var/www/html/symset/public';
protected $uploadDir = 'uploads/';
function __construct()
{
$this->docRoot = $_SERVER['DOCUMENT_ROOT'];
}
function create()
{
return view('files.create', []);
}
function store(Request $request)
{
$input = $request->input();
$title = trim($input['title']);
$validator = Validator::make($request->all(), [
'file' => 'required|mimes:jpeg,png|max:4096',
'title'=> 'required'
]);
if ($validator->fails()) {
return redirect()
->back()
->withErrors($validator)
->withInput();
}
$filePath = '';
if ($request->hasFile('file'))
{
try {
$file = $request->file;
//File Name
$oriName = $file->getClientOriginalName();
// File Extension
$file->getClientOriginalExtension();
// File Real Path
$file->getRealPath();
// File Size
$file->getSize();
// File Mime Type
$file->getMimeType();
// Move file to folder with a unique name to pervent caching
$destinationPath = $this->docRoot . '/' . $this->uploadDir . Str::random(32);
$file->move($destinationPath, $file->getClientOriginalName());
$filePath = str_replace($this->publicDir, '', $destinationPath) . '/' . $oriName;
} catch(\Exception $e){
}
}
$arr = [
'title' => $title,
'file' => $filePath,
'created_at'=>\Carbon\Carbon::now()
];
\DB::table('files')->insert($arr);
return redirect()->back()->with('success', 'Image upload success!!');
}
}
3. The templates
resources/views/layouts/app.blade.php
<html>
<head>
<title>Symset - @yield('title')</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
@section('sidebar')
<!--This is the master sidebar.-->
@show
<div class="container">
@if(session()->has('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
@endif
@yield('content')
</div>
</body>
</html>
resources/views/files/create.blade.php
@extends('layouts.app')
@section('title', 'Learn to upload files')
@section('sidebar')
@parent
<!-- <p>This is appended to the master sidebar.</p> -->
@endsection
@section('content')
<h1>Upload files with Laravel</h1>
<form method="POST" enctype = "multipart/form-data" accept-charset="UTF-8" action="/files">
@csrf
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br> <ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<div class="form-group">
<label for="title">Title</label>
<input name="title" id="title" type="text" class="form-control" value="{{ old('title') }}">
</div>
<div class="form-group">
<input type="file" name="file">
</div>
<div class="form-group">
<input type="submit" value="save" class="btn btn-primary">
</div>
</form>
@endsection