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
By default, Laravel will determine the relationship associated with the given model based on the class name of the model; however, you may specify the relationship name manually by providing it as the second argument to the whereBelongsTo method:
The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform like Laravel Vapor. A Project model might access many Deployment models through an intermediate Environment model.
But now in Laravel latest version Form and HTML libraries are not included by default. Now, Form and HTML are now separate composer packages. So to make use of form builder you have to install laravelcollective/html composer package for form in your laravel application.
Consider upgrading your project to Laravel 9.x . The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With