I have an employees table and a roles table. On the from to create an employee I also wish to assign a role. However my code stores the data with NULL on the foreign key in employees table. How do I make it store the relation?
Employees model.php
class employees extends Model
{
protected $fillable = [
'first_name',
'surname',
];
public function Roles()
{
return $this->belongsTo('App\Roles');
}
Roles model.php
class Roles extends Model
{
protected $fillable = [
'role_name',
];
public function Employees()
{
return $this->hasMany('App\Employees');
}
}`
Controller to create employee
public function store(EmployeesRequest $request)
{
$employee = Employees::find($request);
Employees::create($request->all());
Roles::create($request->all());
$employee->roles()->save($roles);
return redirect()->route('employees.index')->with('message','Employee has been added');
}
On the form I have first_name, surname and role_name. These are saved but with NULL on the role_id column in my employees table? Tried reading the laravel docs but struggling to use ->save method
Current error it is returning is Call to a member function roles() on null