Created
January 21, 2022 04:24
-
-
Save HakamRaza/c7d8ec17852a74bf88c9257383083007 to your computer and use it in GitHub Desktop.
Using Trait inside Models
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\Controller\AbsenceCalendarController; | |
class EmployeeAbsenceCalendar extends Controller | |
{ | |
protected $employee; | |
public function __construct(User $employee) | |
{ | |
$this->employee = $employee; | |
} | |
/* | |
* use by user instance, inside Controller (employee is instance of User) | |
*/ | |
public function index(Request $request) | |
{ | |
return $employee->targetHourDayForDate($request->date), | |
} |
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\Traits; | |
/** | |
* create a trait class containing reusable methods collection | |
* | |
*/ | |
trait HasTargetHours | |
{ | |
public function targetHourDayForDate(Carbon $date) | |
{ | |
return $this->getTargetHour($date) | |
->week_days | |
->getDayForDate($date); | |
} | |
} |
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\Models; | |
/* | |
* example import inside User Model | |
*/ | |
class User extends Authenticatable | |
{ | |
use TargetHours; | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
compile repetitive methods that can be use in numerous independent classes, here imported inside Models. Also can be use inside Controllers.