0

I have this simple Laravel application with on 1 page a table is shown from the database.

Like this:

  @foreach ($cases in $case)
    {{ $case->title }}
    {{ $case->description }}
  @endforeach

There is only one thing which i can't get working. Every case is owned by a user so my database table 'Cases' contains one column named 'owner_id'. I want to show properties of the 'User' owning the 'Case' object.

I've read that doing this kind of coding is not neat to write in the 'view'. But I have no idea how I could do something like this in a controller class because my approach is to do it within the for-loop

Before I have tried to combine the 2 objects so I could access properties of both the user and the case object

$cases = DB::table('cases')->get();

    $userCases = array();

    for ($i=0; $i < count($cases); $i++) {
        $case = $cases[$i];

        $user = DB::table('users')->where('id', $case->owner_id)->first();

        array_push($userCases, array($case, $user);
     }

But this doesn't seem to work as an array is only filled with pointers.

1

1 Answer 1

3

Use a belongsTo-relationship.

In your Case-model, add the following method:

app/models/UserCase.php:
<?php 
class UserCase extends \Eloquent // "Case" is reserved in PHP, so we use a custom name
{
    protected $table = 'cases';
    //....
    public function user() // you could call it owner or whatever
    {
        return $this->belongsTo('User', 'owner_id');    

    }
}

Now, when fetching the cases, don't use the direct query, but instead: $cases = UserCase::all(). For performance reasons, you will want to load the User model so that you dont query the database every time you access user information in the loop. So the real load: $cases = UserCase::with('user')->get();

Now, to fetch information about the user which the case belongs to, you can simply do $case->user->firstname or whatever your column names are. So, building upon your original blade-example, you'd do something like this:

   @foreach ($cases in $case)
        {{ $case->user->firstname }}
        {{ $case->title }}
        {{ $case->description }}
    @endforeach
Sign up to request clarification or add additional context in comments.

3 Comments

Good answer. Just don't forget to eager load the relationship. UserCase::with('user')->get();
Thanks! My hero! <3 no homo though
No homo? So all of this - the spandex suit, the gas mask - for nothing!?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.