How To Use Custom Trait In Laravel Controller

Hello artisan in this laravel 8 trait example i am going to discuss about how to use custom trait in laravel controller. We can use trait and we also use many trait which is laravel trait. But in this example we will create trait and use them as a helper in our controller method.

We all know that PHP implements a way to reuse code called Traits. In PHP trait is a mechanism for code reuse in single inheritance languages such as PHP. In PHP a trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. 

An example of a Trait could be:

trait SharePost {
 
  public function share($item)
  {
    return 'share this post';
  }
 
}

 

We can then include this Trait within other classes like this:

class Post {
 
  use SharePost;
 
}
 
class Comment {
 
  use SharePost;
 
}

//and so on

 

Now if we were to create new objects out of these classes you would find that they both have the share() method available:

$post = new Post;
echo $post->share(''); // 'share this post' 
 
$comment = new Comment;
echo $comment->share(''); // 'share this post'

 

Now see another example of PHP trait. Now in this example we will create our own custom trait and learn how to use them in our laravel controller like inheritance. So let's see the example code to understand.

trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class TheWorldIsNotEnough {
    use HelloWorld;
    public function sayHello() {
        echo 'Hello Universe!';
    }
}

$o = new TheWorldIsNotEnough();
$o->sayHello();

//output
Hello Universe!

 

Now see how we can use this logic in our Laravel application.

app/Traits/ImageTrait.php

namespace App\Traits;
  
use Illuminate\Http\Request;
  
trait ImageTrait {
  
    /**
     * @param Request $request
     * @return $this|false|string
     */
    public function verifyAndUpload(Request $request, $fieldname = 'image', $directory = 'images' ) {
  
        if( $request->hasFile( $fieldname ) ) {
  
            if (!$request->file($fieldname)->isValid()) {
  
                flash('Invalid Image!')->error()->important();
  
                return redirect()->back()->withInput();
  
            }
  
            return $request->file($fieldname)->store($directory, 'public');
  
        }
  
        return null;
  
    }
  
}

 

Now use this trait in your Laravel controller like below style:

app/Http/Controllers/ItemController.php

namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Item;
use App\Traits\ImageTrait;
  
class ItemController extends Controller
{
    use ImageTrait;
    
    public function create()
    {
        return view('imageUpload');
    }
   
    public function store(Request $request)
    {
        $input = $request->all();
   
        $input['image'] = $this->verifyAndUpload($request, 'image', 'images');
   
        Item::create($input);
    
        return back()
            ->with('success','record created successfully.');
   
    }
}

 

Read also: What Does * * * * * (Five Asterisks) in a Cron File Mean?

 

Now, we can use it in our other controller like that. Hope it can help you.

 

#laravel #laravel-8x #laravel-trait #example