akanaan / model-files
A package for laravel to help attaching files to models (images, pdfs, ... etc).
1.0.0
2020-10-04 13:29 UTC
Requires (Dev)
- orchestra/testbench: ^6.1
This package is not auto-updated.
Last update: 2025-06-13 08:58:05 UTC
README
A package for laravel to help attaching files to models (images, pdfs, ... etc).
Installation
Use the package manager composer to install Laravel Model Files.
composer require akanaan/model-files
Run migrate to create tables
php artisan migrate
Usage
The package is very easy to use, just add the trait HasFiles
to the model and create settings array for the files
<?php namespace App\Models; use AKanaan\ModelFiles\Traits\HasFiles; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFiles; protected $attaches = [ 'logo' => [ 'disk' => 'public', 'path' => '/', ], 'images' => [ 'disk' => 'public', 'path' => 'images', ] ]; }
Attach, Detach, Retrieve.
attaching
<?php ... $product = Product::findOrFail($id); $product->attachFile('logo', $request->file('logo')); $product->attachFiles('images', [ $request->file('images.0'), $request->file('images.1'), $request->file('images.2') ... ]); ...
detaching
<?php ... $product = Product::findOrFail($id); $product->detachFile('logo'); /* * Second param is optional (array of ids of files you want to delete) */ $product->detachFiles('images', [1, 2, 3]); ...
retrieving
<?php ... $product = Product::findOrFail($id); // returns instance of AKanaan\ModelFiles\Models\File $product->retrieveFile('logo'); // returns collection of AKanaan\ModelFiles\Models\File $product->retrieveFiles('images'); ...
Public Url
<?php ... $product = Product::findOrFail($id); $logo = $product->retrieveFile('logo'); $publicUrl = $logo->url(); ...