TheBurgerShot TheBurgerShot - 3 days ago 5
PHP Question

Get object depending on other object within for-loop in Laravel

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.

Answer

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
Comments