Created
February 4, 2019 17:21
-
-
Save stockenberg/a917802c5ff97c6b537cf26655e55cfd to your computer and use it in GitHub Desktop.
An Example class to Eager load Tables and Pivot Data
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; | |
use Illuminate\Database\Eloquent\Model; | |
class Alumni extends Model | |
{ | |
// | |
protected $fillable = ['birthdate', 'firstname', 'lastname', 'country', 'teaser', 'fulltext', 'img']; | |
protected $with = ['companies', 'products', 'social_platforms', 'campuses', 'departments']; | |
public static function validationRules(): array | |
{ | |
return [ | |
'alumni.firstname' => 'required', | |
'alumni.lastname' => 'required', | |
'product.course_code' => 'required', | |
'product.achieved_at' => 'required', | |
'alumni.birthdate' => 'required|date', | |
'alumni.country' => 'required', | |
'product.department_id' => 'required', | |
'product.product_id' => 'required', | |
'product.campus_id' => 'required', | |
]; | |
} | |
public function getExpirationAttribute($value) | |
{ | |
$current_date = date('d.m.Y'); | |
$enddate = strtotime($value); | |
$diff = $enddate - time(); | |
$days = floor($diff/(60*60*24)); | |
$hours = round(($diff-$days*60*60*24)/(60*60)); | |
return [ | |
'timestamp' => strtotime($value), | |
'dateTime_string' => $value, | |
'days' => $days, | |
'hours' => $hours, | |
]; | |
} | |
public function companies() | |
{ | |
return $this->belongsToMany(Company::class)->withPivot('current', 'position', 'employment_started', 'employment_ended'); | |
} | |
public function products() | |
{ | |
return $this->belongsToMany(Product::class)->withPivot(['course_code', 'achieved_at']); | |
} | |
public function social_platforms() | |
{ | |
return $this->belongsToMany(SocialPlatform::class); | |
} | |
public function departments() | |
{ | |
return $this->belongsToMany(Department::class, 'alumni_product', 'alumni_id', 'department_id'); | |
} | |
public function campuses() | |
{ | |
return $this->belongsToMany(Campus::class, 'alumni_product', 'alumni_id', 'campus_id'); | |
} | |
public function user() | |
{ | |
return $this->belongsTo(User::class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment