3

First things first, this is not a duplicate of Laravel 4: how to "order by" using Eloquent ORM

I have this model User, then I have this other model Idea. I'm writting a view with the details of the user, and I want to post all the ideas the user has suggested. Now, the ideas have a status, the first status is "DRAFT", that means only the user who posted the idea can review it, the idea should not be shown to other users looking at the profile.

Using eloquent I could do something like:

@foreach($user->idea as $idea)
    ...display details...
@endforeach

My problem is that this approach would cycle through all ideas AND in the order where they were introduced. I can add an @if to show only what I want, like

@foreach($user->idea as $idea)
    @if($idea->status !='DRAFT')
        ...show the idea...
    @endif
@endforeach

But I don't think it's the smart way to do it, I'd like to do something like

$ideas = $user->idea->where('status', '<>', 'DRAFT')

and then cycle through the $ideas variable, or at least, I'd like somtehing like

$ideas = $user->idea->orderBy('created_at', 'desc')

But I have no idea on how to do it.

luisfer
  • 1,927
  • 7
  • 40
  • 54

2 Answers2

6

You can do it like this:

$ideas = $user->idea()
    ->where('status', '<>', 'DRAFT')
    ->orderBy('created_at', 'desc')
    ->get();

When you use ->idea() it will start a query.

For more information about how to query a relationship: https://laravel.com/docs/5.7/eloquent-relationships#querying-relations

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
1

You can user where clause like this

DB::table('products_to_categories')
    ->where('categories_id', $id )
    ->update([
        'categories_id' => $unassigned_cat_id
    ]);

and you can use orderBy clause like this

DB::table('products_to_categories')
    ->where('categories_id', $id )
    ->orderBy('subId','DESC');