I want to ask for your help.
I'm studying laravel, i am using laravel 10, and I need to retrieve related data, the application and data that I'm working on are related to students in a school. I want to retrieve student data with their angkatan
. here's the context I'm thinking about.
all students each have 1
angkatan
, whether it's the same as other students or different.
here is the code that i wrote on the model and controller in my learning project.
Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Siswa extends Model
{
use HasFactory;
protected $table = 'siswa';
protected $primaryKey = 'id';
// semua siswa memiliki 1 angkatan
public function angkatan()
{
return $this->belongsTo(Angkatan::class, 'angkatan', 'id');
}
}
Controller
namespace App\Http\Controllers;
use App\Models\Siswa;
use Illuminate\Http\Request;
class SiswaController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
// siswa with angkatan where angkatan = angkatan.id
$siswa = Siswa::with('angkatan')->first();
$test = "ini adalah test";
return view('siswa', compact('siswa', 'test'));
}
}
when I did dump()
I found that the batch was obtained successfully, here is the result of the dump that I got
{
"id": 1,
"user_id": 15,
"nis": "4994247",
"nama": "Radika Mandala",
"kelas": "XI TKJ",
"angkatan": {
"id": 2,
"tahun": "2023",
"nama": "2023 Gelombang 2",
"tgl_mulai": "2023-05-05",
"tgl_selesai": "2023-07-05",
"created_at": "2023-06-04T11:20:43.000000Z",
"updated_at": "2023-06-04T11:20:43.000000Z",
"deleted_at": null
},
"no_hp": "+96168988859",
"alamat": "Ki. Industri No. 881",
"laporan": null,
"created_at": "2023-06-04T11:20:44.000000Z",
"updated_at": "2023-06-04T11:20:44.000000Z",
"deleted_at": null
}
however when trying to access it directly in the view linked with the following code {{ dump($siswa->angkatan->tahun) }}
I get an error Attempt to read property "tahun" on int
I didn't find the problem where, because from the results returned from the controller data angkatan
should have been successfully obtained, unfortunately in this case I only used the database that was already created, without making migrations or other things in Laravel that I was working on,
You can't have a field (attribute) and a relationship with the same name since you are trying to access your data via dynamic properties, $model->property
. It can only resolve that to either the actual field (attribute) or the relationship.
The column on the table should be ankatan_id
and the relationship would be as it currently is ankatan
. Now there is no ambiguity, ankatan_id
is the field and ankatan
is the relationship.
$model->ankatan_id // field (attribute)
$model->ankatan // relationship dynamic property
If you can't change your schema you could change the name of the relationship.