Skip to content

Instantly share code, notes, and snippets.

@HakamRaza
Created January 21, 2022 04:18
Show Gist options
  • Save HakamRaza/54732f87cc5603252a60a7b56784bb4d to your computer and use it in GitHub Desktop.
Save HakamRaza/54732f87cc5603252a60a7b56784bb4d to your computer and use it in GitHub Desktop.
Using Traits inside Laravel Controller
<?php
use App\Http\Traits\StudentTrait;
class AnotherController extends Controller
{
use StudentTrait;
/**
* using trait inside another controller
*
*/
public function index(Request $request)
{
return $this->allStudentActive()
->where('created_at', Carbon::today);
}
}
<?php
use App\Http\Traits\StudentTrait;
class UserController extends Controller
{
use StudentTrait;
/**
* using trait inside controller
*
*/
public function index(Request $request)
{
return $this->allStudentActive();
}
}
<?php
namespace App\Http\Traits;
use App\Models\Student;
/**
* create a trait class containing reusable methods collection
*
*/
trait StudentTrait
{
public function allStudentActive()
{
return Student::where('attend', 1)->get();
}
//...
}
@HakamRaza
Copy link
Author

compile repetitive methods inside trait that can be use in numerous independent classes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment