0

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,

HALIM
  • 63
  • 8

2 Answers2

1

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.

lagbox
  • 48,571
  • 8
  • 72
  • 83
  • If I'm not wrong the default `relationship name` is the `method name`. You can change this by passing the desire `relationship name`. `$this->belongsTo(Angkatan::class,'angkatan','id', 'relation_name');` – xenooooo Jun 04 '23 at 14:48
  • @lagbox thanks to you I found out at the time the problem, let me explain it. so in student column i have a column named `angkatan`, it will be a problem when you declare a function to call relation in your model with the same name, i.e. `angkatan`. and to solve this problem you can rename your relation with a different name, for example, `angkatan_detail`. model :`function angkatan_detail() {....}` and is called with `Siswa::with('class_detail')` in the **controller**. thanks – HALIM Jun 04 '23 at 15:01
0

The relationship between the Siswa model and the Angkatan model is not being set correctly. The error message "Attempt to read property 'tahun' on int" means that the angkatan attribute of the $siswa object is an integer instead of an object.

Make sure that the foreign key column angkatan in the siswa table references the primary key column id in the angkatan table.

Create a migration file to add the foreign key column to the siswa table. Run the following command to generate the migration file:

php artisan make:migration add_angkatan_to_siswa --table=siswa

In the generated migration file, add this inside the up() function

public function up()
{
    Schema::table('siswa', function (Blueprint $table) {
        $table->foreignId('angkatan')->constrained('angkatan');
    });
}

Finally, run the command in your project

php artisan migrate

In the Siswa model, update the belongsTo relationship definition.

public function angkatan()
{
    return $this->belongsTo(Angkatan::class, 'angkatan', 'id');
}
hareth py
  • 112
  • 6
  • thanks for the suggestion, but unfortunately I can't do that, because an error occurs Cannot add or update a child row. but what I get from your point is that to ensure that the angkatan column in the student table points to the primary column in the angkatan table. therefore to be able to get help from you I attach the following two pictures [relation view](https://prnt.sc/Ru9f02XK93TQ) and [desain relation](https://prnt.sc/x-D4KyJsU62R) – HALIM Jun 04 '23 at 14:21
  • Are both columns max sql length the same? – hareth py Jun 04 '23 at 15:04