I'm new in Laravel about a few weeks and now I'm currently learning Relationship task. I have been searching related topics about it but I don't have a clue why my code is not working.
I have 2 tables Employee & Phone:
Employee:
- ID int
- Name varchar
- Age int
- Position varchar
- Address varchar
- created_at timestamp
- update_at timestamp
- deleted_at timestamp
Phone:
- ID int
- No varchar
- Employee_ID int
I'm using Laravel v.8
Models: PhoneS.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PhoneS extends Model
{
use HasFactory;
protected $table = "Phone";
public function EmployeeS()
{
return $this->belongsTo('App\Models\EmployeeS', 'Employee_ID', 'ID');
}
}
Models: EmployeeS.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class EmployeeS extends Model
{
use HasFactory;
protected $table = "Employee";
public function PhoneS()
{
return $this->hasOne('App\Models\PhoneS', 'Employee_ID', 'ID' );
}
}
Controller: Phone.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmployeeS;
class Employee extends Controller {
public function index()
{
$EmployeeS = EmployeeS::all();
return $EmployeeS;
}
}
The result:
[
{
"ID": 1,
"Name": "John",
"Age": 26,
"Position": "IT",
"Address": "Boulevard street",
"created_at": null,
"updated_at": null,
"deleted_at": null
},
{
"ID": 2,
"Name": "Doe",
"Age": 25,
"Position": "Acc",
"Address": "Avenue street",
"created_at": null,
"updated_at": null,
"deleted_at": null
},
...
...
]
There's no field: PhoneS there...
and when I try to access it with: return $EmployeeS->PhoneS, it gives error message:
Exception
Property [PhoneS] does not exist on this collection instance.
Can anyone let me know what happen?
I believe there's something I missed about Laravel Relationship concept.
Can you pointing me where I got missed?
Thanx in advance..