Skip to content

Instantly share code, notes, and snippets.

@HakamRaza
Created January 21, 2022 04:24
Show Gist options
  • Save HakamRaza/c7d8ec17852a74bf88c9257383083007 to your computer and use it in GitHub Desktop.
Save HakamRaza/c7d8ec17852a74bf88c9257383083007 to your computer and use it in GitHub Desktop.
Using Trait inside Models
<?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),
}
<?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);
}
}
<?php
use App\Models;
/*
* example import inside User Model
*/
class User extends Authenticatable
{
use TargetHours;
//...
}
@HakamRaza
Copy link
Author

compile repetitive methods that can be use in numerous independent classes, here imported inside Models. Also can be use inside Controllers.

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