How to use laravel traits

527 0 0 0

Last Updated : 2024-03-29 00:32:39

In this snippet I will teach you how to use laravel traits effectively

Laravel traits is a piece of code that can be reused in any controller or model .

First Step: create trait php file in app folder or any folder you want

Second Step: 
this is the content of trait file like this


<?php
namespace App\Traits; //Trait namespace

use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;

trait ImageTrait
{

/**
* Delete Image function
*
* @param $img
* @param $path
*/
protected function deleteImage($image = null, $path = '')
{
if (File::exists(public_path($path . $image))) {
File::delete(public_path($path . $image));
}
}

}

Third Step: use the trait in any controller you want like this


<?php

namespace App\Http\Controllers;

use App\Traits\ImageTrait;

class ServiceController extends Controller
{

use ImageTrait;

/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$this->deleteImage();
}

}

 

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.