Php Laravel Get File Handler From Upload File
In this post, I will be going to share how to implement a elementary Laravel 8 file upload with a database implementation. We will salve the generated file name base on time, size, mime-blazon, and associate information technology with the current user logged. When developing an application using Laravel unremarkably the file upload is always present even on a simple system.
Only follow my simple steps and larn from them.
I presume that you lot have your Laravel 8 Project already in your local so we will skip that process. For more than information on how to install Laravel just visit their documentation.
Okay, let's showtime.
Pace 1: Create file upload migrations
First, nosotros will create our files table migrations for our File model. Run the following command to do information technology:
php artisan make:migration create_files_table
Then we will add our migrations field. Come across below the complete code for our migrations.
<?php use Illuminate\Database\Migrations\Migration; apply Illuminate\Database\Schema\Blueprint; utilise Illuminate\Support\Facades\Schema; class CreateFilesTable extends Migration { /** * Run the migrations. * * @render void */ public function up() { Schema::create('files', function (Blueprint $table) { $table->id(); $tabular array->unsignedBigInteger('user_id'); $tabular array->cord('name'); $table->cord('type'); $tabular array->string('size'); $table->timestamps(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @render void */ public role downward() { Schema::dropIfExists('files'); } }
Side by side, you have to run:
php artisan migrate
Footstep 2: Create file upload controller and model
Utilise the command below to create your FileController with File model:
php artisan make:controller FilesController --model=File
Step iii: Create file upload routes
Now, allow's create your routes for our file upload:
/** * File Upload Routes */ Route::get('/files', 'FilesController@index')->proper name('files.alphabetize'); Route::get('/files/add', 'FilesController@create')->name('files.create'); Road::post('/files/add together', 'FilesController@store')->proper name('files.store');
Step 4: Setup Model
Adjacent, nosotros will gear up our File model. See below the completed setup.
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; apply Illuminate\Database\Eloquent\Model; course File extends Model { protected $tabular array = 'files'; protected $fillable = [ 'user_id', 'name', 'blazon', 'size' ]; utilize HasFactory; }
Step v: Setup Controller
Kindly come across beneath the consummate lawmaking of our controller including the file upload in store() method.
<?php namespace App\Http\Controllers; use App\Models\File; use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; utilise App\Http\Requests\StoreFileRequest; course FilesController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public part index() { $files = File::all(); return view('files.alphabetize', [ 'files' => $files ]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { render view('files.create'); } /** * Store a newly created resource in storage. * * @param StoreFileRequest $asking * @render \Illuminate\Http\Response */ public function store(StoreFileRequest $request) { $fileName = auth()->id() . '_' . time() . '.'. $request->file->extension(); $type = $request->file->getClientMimeType(); $size = $request->file->getSize(); $request->file->move(public_path('file'), $fileName); File::create([ 'user_id' => auth()->id(), 'name' => $fileName, 'type' => $blazon, 'size' => $size ]); return redirect()->route('files.index')->withSuccess(__('File added successfully.')); } }
Pace 6: Create StoreFileRequest
At present let'southward create a request grade for a store/uploading file. Run the command beneath:
php artisan make:request StoreFileRequest
After the StoreFileRequest course is generated kindly bank check the code below for our validation:
<?php namespace App\Http\Requests; utilize Illuminate\Foundation\Http\FormRequest; class StoreFileRequest extends FormRequest { /** * Determine if the user is authorized to brand this request. * * @return bool */ public function qualify() { return true; } /** * Get the validation rules that use to the request. * * @return array */ public function rules() { render [ 'file' => 'required|file|mimes:jpg,jpeg,bmp,png,doc,docx,csv,rtf,xlsx,xls,txt,pdf,zip' ]; } }
Step seven: Create View
First, we will create our index.blade.php run across below the complete lawmaking:
@extends('layouts.app-principal') @section('content') <div form="bg-calorie-free p-v rounded"> <h1>Files</h1> <a href="{{ route('files.create') }}" class="btn btn-chief float-right mb-3">Add together file</a> @include('layouts.partials.messages') <table class="table tabular array-striped"> <thead> <tr> <th telescopic="col">#</th> <th telescopic="col">Proper noun</thursday> <th scope="col">Size</thursday> <th scope="col">Blazon</th> <th scope="col">Action</th> </tr> </thead> <tbody> @foreach($files equally $file) <tr> <td width="3%">{{ $file->id }}</td> <td>{{ $file->proper noun }}</td> <td width="x%">{{ $file->size }}</td> <td width="10%">{{ $file->type }}</td> <td width="5%"><a href="{{ $file->type }}" class="btn btn-danger btn-sm">Delete</a></td> </tr> @endforeach </tbody> </table> </div> @endsection
Second, create.blade.php for our uploading file.
@extends('layouts.app-main') @section('content') <div grade="bg-light p-5 rounded"> <h1>Add together file</h1> <form action="{{ route('files.store') }}" method="mail service" enctype="multipart/form-information"> @include('layouts.partials.messages') @csrf <div form="form-grouping mt-4"> <input type="file" proper noun="file" class="form-control" accept=".jpg,.jpeg,.bmp,.png,.gif,.doc,.docx,.csv,.rtf,.xlsx,.xls,.txt,.pdf,.zilch"> </div> <push class="westward-100 btn btn-lg btn-master mt-four" type="submit">Save</button> </class> </div> @endsection
As you can see from our input=file nosotros added accept attribute with a value of ".jpg,.jpeg,.bmp,.png,.gif,.doc,.docx,.csv,.rtf,.xlsx,.xls,.txt,.pdf,.zip" information technology will help to only accept base of operations on specified file extensions.
Download Source Lawmaking
Thank you for reading. I hope it helps.
Happy coding :)
Source: https://codeanddeploy.com/blog/laravel/laravel-8-file-upload-example
0 Response to "Php Laravel Get File Handler From Upload File"
ارسال یک نظر