skip to Main Content

I am thinking how to write smartest this code:

Controller:

$tasks = Task::where('department', '=', $department)
->orderBy('created_at', 'DESC')
->get();

In blade file I write:

@foreach($tasks as $task)
@if($task->status == 1)
<tr>
    <td class="cell">#{{ $task->id }}</td>
    <td class="cell">{{ $task->title }}</td>
</tr>
@endif
@endforeach

LOT OF HTML

@foreach($tasks as $task)
@if($task->status == 2)
<tr>
    <td class="cell">#{{ $task->id }}</td>
    <td class="cell">{{ $task->title }}</td>
</tr>
@endif
@endforeach

Is it possible to foreach not all elements, but only with $task->status == 1 ? then only $task->status == 2 and etc? Because there will be very long loops with unwanted statuses. I think that it is possible to do with GroupBy function, but do not find the way. Examples I found on the internet do not fit my requirements.

P.S. The best would be to use forelse instead foreach to display information when sector is empty, but in this way I get a lot of bigger code than usual.

Please offer me shortest and most traffic-friendly method

2

Answers


  1. You can create two different variables. like this.

    $firstTasks = Task::where('department', $department)
    ->orderBy('created_at', 'DESC')
    ->where('status', 1)
    ->get();
    
    $secondTasks = Task::where('department', `enter code here`$department)
    ->orderBy('created_at', 'DESC')
    ->where('status', 2)
    ->get();
    
    Login or Signup to reply.
  2. You can simply add another ordeyBy function on status so it wil sort the record by status as well and you can simply display all record with single loop.

     $tasks = Task::where('department', '=', $department) 
     ->orderBy('created_at', 'DESC')
     ->orderBy('status', 'ASC') 
     ->get();
    
     @foreach($tasks as $task)
        <tr>
           <td class="cell">#{{ $task->id }}</td>
           <td class="cell">{{ $task->title }}</td>
        </tr>
     @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search