Here We going to see how to upload images or other files, using Traits that can be used in a multiple Controllers without stuffing the Controllers page with unneeded code.

 

Traits in general are used when we need multiple methods in a different classes. A perfect example is when we need to upload a file / image in the WYSIWYG editor, but also in Videos, Articles, etc...

 

First We going to create a Trait Folder , in App

 

<?php
namespace App\Traits;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

trait UploadTrait
{

    // upload an image

    public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
    {
        $name = !is_null($filename) ? $filename : str_random(15);

        $file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);

        return $file;
    }
}

Now lets see how to use it in a Controller. Lets say We have an App\Article Model, and an Admin Controller App\Http\Controllers\Admin\ArticleController.php

First we are Using the trait:

use App\Traits\UploadTrait;
class ArticleController extends Controller
{
use UploadTrait;
/**
if ($request->has('feautured_image')) {
// Get image file
$image = $request->file('feautured_image');

$name = $article->slug;
$folder = 'articlesrepo';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
// Upload image
$uploaded = $this->uploadOne($image, $folder, 'public_uploads', $name);


$article->image = 'uploads/' . $uploaded;



}

 

First we get the image from the request in the $image variable, then we save the $folder, and $filepath, and finally we just use $uploaded = $this->uploadone() method from the Trait we created.

Thats it, dont forget to ->save() outside of the if ($request->has('feautured_image'))