user3359775
user3359775

Reputation: 119

laravel 4: order object in template

I'm trying to order the tests for each user in descending order of created_at. I tried it in the template but I didn't succeed. These are my tables:

 | users      |   | courses    |    | tests      |
 | ---------- |   |------------|    |------------|
 | id         |   | id         |    | id         |
 | name       |   | name       |    | name       |
 | created_at |   | created_at |    | created_at |
                  | user_id    |    | course_id  |

A user has many courses and a course has many tests. I'll like to order all the tests in descending order of created_at.

I tried this in my template:

@foreach(User::find($user->id)->courses as $course)
        @foreach(Course::find($course->id)->tests as $test)
            <p>Name: {{$test->name}}</p>
            <p>Date: {{$test->created_at}}</p>
        @endforeach
@endforeach

Edit: There are my models

User.php

   public function courses()
   {
    return $this->hasMany('Course');
   }

Course.php

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

   public function test()
    {
    return $this->hasMany('Test');
    }

Test.php

   public function courses()
    {
    return $this->belongsTo('Course');
    }

Upvotes: 1

Views: 61

Answers (2)

The Alpha
The Alpha

Reputation: 146239

You may try this, do it in your Controller:

$users = User::with(array('courses.tests' => function($query) {
    $query->orderBy('tests.created_at', 'desc');
}))->find($user->id);

Then load the view and pass the $user object like this:

return View::make('your_view_name')->withuser($user);

Then in your view try something like this:

@foreach($user->courses->tests as $test)
        <p>Name: {{ $test->name }}</p>
        <p>Date: {{ $test->created_at }}</p>
@endforeach

Upvotes: 1

Gregorio Setti
Gregorio Setti

Reputation: 321

You could simply add the orderBy command to your query, like:

@foreach($user->courses as $course)
    @foreach($course->tests()->orderBy('created_at', DESC)->get() as $test)
        <p>Name: {{$test->name}}</p>
        <p>Date: {{$test->created_at}}</p>
    @endforeach
@endforeach

Look that it's not a good practice to make queries in the views, so I changed your query in some variables you should be setting in your controller. Also change test() method to tests(), because it's a one-to-many relation, and it's clearer to have plurals as method name.

Upvotes: 1

Related Questions