Edvard Åkerberg Edvard Åkerberg - 5 months ago 31
MySQL Question

Laravel 5 model class not found - hasMany

I am trying to get company employees using the has many method in model. But I get this error.

Fatal error: Class 'Employee' not found (View: /home/vagrant/Code/laravel/resources/views/frontpage.blade.php)


Here is my controller:

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Company;
use App\Employee;

public function index()
{
$data = Company::get();
$data = array(
'companies' => $data,
);


return view('frontpage', $data);
}


And here is my models: first one is Company.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Employee;

class Company extends Model{

protected $table = 'company';

public function employee()
{
return $this->hasMany('Employee', 'company_id', 'id');
}
}


Here is the other model, Employee.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model{

public $table = "employee";

}


And here is the view

@extends('layouts.master')

@section('content')

<div>
@foreach ($companies as $company)
<p>This is company {{ $company->name }}</p>
<p>{{ print_r($company->employee) }}</p>
@endforeach
</div>

@stop

Answer

Relation definitions require fully qualified class names to be passed.

Replace

return $this->hasMany('Employee', 'company_id', 'id');

with either

return $this->hasMany('App\Employee', 'company_id', 'id');

or

return $this->hasMany(Employee::class, 'company_id', 'id');
Comments