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?
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');
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With