Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

share method between controllers Laravel 5.2

In several controllers i have to use the same method to show results as table with column sorting functionality:

 public function showSearchResults(Request $req){

        $query=Service::where('title', $req->search);

        // Columns sorting 
        if ($req->has('order')){
            $order= $req->order=='asc' ? 'asc' : 'desc';
            $order_inverse=$req->order=='asc' ? 'desc' : 'asc';
        } else {
            $order='desc';
            $order_inverse='asc';
        }

         ...


        $url=$req->url().'?'.http_build_query($req->except('sortby','order','page'));
        $results=$query->with('type')->paginate(15)->appends($req->all());


        return View::make('services.search_results')
                    ->with('results', $results)
                    ->with('url',$url)
                    ->with('sortby', $sortby)
                    ->with('order', $order)
                    ->with('order_inverse', $order_inverse);

    }

What is the best approach to avoid DRY in such case?

like image 237
user947668 Avatar asked Apr 25 '16 13:04

user947668


People also ask

What is RESTful controller in laravel?

RESTful Resource Controllers The Artisan command will generate a controller file at app/Http/Controllers/PhotoController. php . The controller will contain a method for each of the available resource operations. Next, you may register a resourceful route to the controller: Route::resource('photo', 'PhotoController');

What is Route resource laravel?

Route::resource: The Route::resource method is a RESTful Controller that generates all the basic routes required for an application and can be easily handled using the controller class.


1 Answers

Sharing methods among Controllers with Traits

Step 1: Create a Trait

<?php // Code in app/Traits/MyTrait.php

namespace 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.php

namespace 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.

like image 102
heisian Avatar answered Oct 24 '22 11:10

heisian