jcadima
8/29/2018 - 2:06 PM

File Uploader Trait

1) Create tStoreFile in App\Traits


2)
- $file: request of type file
- $model: specified Model
- $directory: location in /public/{directory} , defaults to /cms
- $field: column field for $model

<?php 

namespace App\Traits;

use Illuminate\Http\Request;

trait tStoreFile{

	public function StoreFile( $file, $model , $directory = '/cms', $field ) {

        $filename =  uniqid() . '_' . $file->getClientOriginalName()  . '.' . $file->getClientOriginalExtension() ;
        $file->move( public_path( $directory ), $filename );
        $model->$field =  $filename;
        $model->save() ;
	}

}

// This will produce a unique file name so that previous files are not overwritten
// 5b7f005030df8_bamboo.jpg


3) In your Controller:
use App\Traits\tStoreFile;
inside class:
use tStoreFile; 


inside your method where a file needs to be stored:

this can be used when storing a record:
$property = Property::create([
	...
]);

OR when updating a record:
$property = Property::find($id);

// $property is the model 
// /properties is the directory inside public where this file will be stored
// 'image' is the name of the column field of this file


if( $request->hasFile('image') ) 
    $this->StoreFile( $request->file('image'), $property, '/properties', 'image' ) ;