Home > Mobile >  Laravel Display foreign key table value
Laravel Display foreign key table value

Time:08-25

Basically I have 2 tables, which is maintenance and user here. I would like to display user name from maintenance table. The following error occurred in my code:

Attempt to read property "name" on int

I tends to find existing solution on StackOverflow. However, most of them are returning model in the controller, such as $maintennace = Maintenance::with(['user']); into the view. However, I was returning DB so I am not sure how to solve this problem.

MaintenanceController

public function ViewMaintenance() {
    $id = Auth::user()->id;
    $maintenance = DB::table('maintenances')->where('landlord_id', $id)->paginate(5);

    return view('maintenance.maintenance-status', compact('maintenance'));
}

Maintenance Model

class Maintenance extends Model
{
    protected $fillable = [
        'title',
        'description',
        'document',
        'category',
        'status',
        'landlord_id',
        'tenant_id',
        'property_id',
    ];

    public function user(){
        return $this->belongsTo('App\Models\User');
    }
}

User Model

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $fillable = [
        'name',
        'username',
        'role',
        'email',
        'avatar',
        'password',
        'phone_number'
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function maintenance() {
        return $this->hasMany('App\Models\Maintenance');
    }
}

The info that I would want to display is name from user database. For your information landlord_id is foreign key based on user table id.

**{{ $maintain-> landlord_id ->name}}**

Maintenance.blade.php

<tbody>
    @if (!empty($maintenance) && $maintenance ->count())
        @foreach ($maintenance as $key=>$maintain)
        <tr>
            <td>{{   $key }}</td>
            <td>{{ $maintain-> title}}</td>
            <td>{{ $maintain-> title }}</td>
            <td>{{ $maintain-> category }}</td>
            @if ($maintain-> status =='Unresolved')
                <td><span >{{ $maintain-> status}}</span></td>
            @endif
            @if ($maintain-> status =='Resolved')
                <td><span >{{ $maintain-> status}}</span></td>
            @endif
            <td>**{{ $maintain-> landlord_id ->name}}**</td>
        </tr>
        @endforeach
    @else 
        <tr>
            <td colspan="6"> There are no data</td>
        </tr>
    @endif
</tbody>

Database Images:

Table User

Table Maintenance

CodePudding user response:

You might be using the Query Builder rather than Eloquent ORM but the principle remains the same. You can't call a property on a non-object.

As you've highlighted the issue lies with:

{{ $maintain->landlord_id->name }}

Where landlord_id is an int, not an instance of your related model (assumingly called Landlord?).

Laravel does a lot of 'magic' for us (which is part of its attraction for some people) but it doesn't know your intent and therefore doesn't automatically load relationships and, foreign keys are not converted to their related model. You still need to do that.

Unless you have a particular reason for using the Query Builder, leverage the Eloquent ORM (another benefit of Laravel) and keep things simple. Define a relationship in your Maintenance model and use that elsewhere.

public function landlord()
{
    return $this->belongsTo(\App\Models\Landlord::class);
}

Then in your controller:

$maintenance = Maintenance::with('landlord')
                ->where('landlord_id', Auth::user()->id)
                ->paginate(5);

CodePudding user response:

In you MaintenanceController

$id = Auth::user()->id;
$maintenance = DB::table('maintenances AS m')->leftJoin('users AS u', 'm.landlord_id', '=', 'u.id')->where('u.id', '=', $id)->get()->paginate(5)

After that, you just display user name.

{{ $maintenance->name }}

You can do test before executing code in MaintenanceController.

dd($maintenance);

CodePudding user response:

Change your relation to

public function user(){
    return $this->belongsTo('App\Models\User', 'landlord_id', 'id');
}

Because you are using landlord_id rather than user_id

  • Related