share method between controllers Laravel 5.2 share method between controllers Laravel 5.2 laravel laravel

share method between controllers Laravel 5.2


Sharing methods among Controllers with Traits

Step 1: Create a Trait

<?php // Code in app/Traits/MyTrait.phpnamespace App\Traits;trait MyTrait{    protected function showSearchResults(Request $request)    {        // Stuff    }}

Step 2: use the Trait in your Controller:

<?php // Code in app/Http/Controllers/MyController.phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use App\Traits\MyTrait; // <-- you'll need this line...class MyController extends Controller{    use MyTrait; // <-- ...and also this line.    public function getIndex(Request $request)    {        // Now you can call your function with $this context        $this->showSearchResults($request);    }}

Now you can use your Trait in any other controller in the same manner.

It is important to note that you don't need to include or require your Trait file anywhere, PSR-4 Autoloading takes care of file inclusion.

You can also use Custom Helper classes as others have mentioned but I would recommend against it if you only intend to share code among controllers. You can see how to create custom helper classes here.


You can use traits (as ventaquil suggested) or you can create custom helpers file and add helpers there.

After that, you'll be able to use this helper from any class (controllers, models, custom classes, commands etc) like any other Laravel helper.