How to see table fields from foreign keys in Laravel

后端 未结 3 804
小蘑菇
小蘑菇 2021-01-26 10:04

I\'m new at Laravel and not good with syntax. I want to see the values of another table through the foreign key(id of that table).

https://ibb.co/pXRFRHn You can see in

3条回答
  •  再見小時候
    2021-01-26 10:35

    It is pretty easy to do exactly what you want. Laravel is great at creating relations.

    You'll need to have the class model set up as a relation on your user model. See the docs on how to do that

    Should be something close to this in the User Model:

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

    Then, when you pull the users from the database in the controller, you can include the relationship directly:

    $users= \App\User::with('class')->get();
    

    Now, you have the related class model within your collection for each of your users, you can pull the name directly as you wish within your blade view:

    @foreach($users as $user)
       {{$user->class->name}}
    @endforeach
    

    I suggest testing with this simple dump above first, as this will work. Then, you can try attaching the different models like the categories afterward.

    By the way - using Class as a class name is probably going to cause you issues. Suggest a slight change there.

    HTH

提交回复
热议问题