0

I have a foreach loop and I want to sort the list by showing records where is_active is null first, then anything else after.

    @foreach ($registrations->sortBy('is_active') as $registration)

Any ideas?

  • do you want to show only is_active = null or do you want to orderBy is_active descending ? – simonecosci Nov 16 '18 at 11:54
  • i want to show the records where is_active null at the top. Then is is_active has a value, they are below the null records. –  Nov 16 '18 at 11:54
  • $registrations->orderByDesc('is_active')->orderByDesc(...) ->get() should do it – simonecosci Nov 16 '18 at 11:56
  • what is the second sort by for? –  Nov 16 '18 at 11:58
  • in case of same is_active ... if 2 records share 'is_active' (eg. null) then the second orderBy will be used – simonecosci Nov 16 '18 at 12:00
  • Possible duplicate of [What is the syntax for sorting an Eloquent collection by multiple columns?](https://stackoverflow.com/questions/25451019/what-is-the-syntax-for-sorting-an-eloquent-collection-by-multiple-columns) – hktang Nov 16 '18 at 12:00
  • @simonecosci thats not doing it. The is_active record is still bottom not top –  Nov 16 '18 at 12:03

2 Answers2

2

first of all make a query that returns records in ascending order according to is_active value( I'm assuming that 0 is for inactive and 1 is for active)

Query should be:

$records=DB::table('table_name')->orderBy('is_active','asc')->all();
return view('viewblade')->with('records',$records);

now you can display data in viewblade like:

@foreach($records as $record){
   {{$record->fieldName}}
}
@endforeach
Vhndaree
  • 594
  • 1
  • 6
  • 20
  • If this solution works or not depends on the database system being used. Not all DBMS are using the same default ordering and some even allow for special order treatment of `NULL` values. – Namoshek Nov 16 '18 at 12:16
0

You can try this way,

 // specify second_column that will be used if multiple null values found

 $registrations = $registrations->sortByDesc('second_column')->sortBy('is_active');

 @foreach ($registrations->all() as $registration)
Mayank Majithia
  • 1,916
  • 16
  • 21