Created
January 21, 2022 04:18
-
-
Save HakamRaza/54732f87cc5603252a60a7b56784bb4d to your computer and use it in GitHub Desktop.
Using Traits inside Laravel Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use App\Http\Traits\StudentTrait; | |
class UserController extends Controller | |
{ | |
use StudentTrait; | |
/** | |
* using trait inside controller | |
* | |
*/ | |
public function index(Request $request) | |
{ | |
return $this->allStudentActive(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
compile repetitive methods inside trait that can be use in numerous independent classes