Eloquent Models
Now that we have our migrations set up, let's create our Eloquent Models.
Note that we're adding a Trait from Lighthouse that will provide us with a helper function to handle Relay Connections.
User Model
// app/User.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Nuwave\Lighthouse\Support\Traits\RelayConnection;
class User extends Authenticatable
{
use Notifiable, RelayConnection;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* Jobs user has created.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function jobs()
{
return $this->hasMany(Job::class);
}
/**
* Tasks assigned to user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToManyk
*/
public function tasks()
{
return $this->belongsToMany(Task::class)->withTimestamps();
}
}
Job Model
// app/Job.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Nuwave\Lighthouse\Support\Traits\RelayConnection
class Job extends Model
{
use RelayConnection;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['title'];
/**
* The user who created the task.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Items that belongs to the task.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function tasks()
{
return $this->hasMany(Task::class);
}
}
Task Model
// app/Task.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Nuwave\Lighthouse\Support\Traits\RelayConnection
class Task extends Model
{
use RelayConnection;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['title'];
/**
* The task the item belongs to.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function job()
{
return $this->belongsTo(Job::class);
}
/**
* User who completed the item.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function completedBy()
{
return $this->belongsTo(User::class);
}
/**
* Users assigned to the item.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(User::class);
}
}