Robin
Robin

Reputation: 1587

Laravel global loop

I'm trying to loop something (alerts) globally into my view.

So I want to do something like this in my view:

@foreach($alert as $alert)
<div class="alert alert-{{ $alert->type }}" role="alert">{{ $alert->message }}</div>
@endforeach

But, When I do this inside my BaseController:

public function __construct() { 

        $get_alerts = Alert::orderBy('id', 'DESC')->whereNull('deleted_at')->get();
        foreach ($get_alerts as $alert) {

            //make an array object of the alerts
            $alert = array();
        }

        return View::share('alert', $alert);
    }

And I {{ dd($alert) }} then I get this output: array(0) { } What isn't what I want...

How Can I fix this on a clean and good manner?

Kindest regards,

Robin

Upvotes: 1

Views: 76

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25374

There are a few issues with your code. This line is the most important:

$alert = array();

What you're saying here is that "for every result in $get_alerts, set $alert to an empty array". That is why you get the output array(0) { } - it's an empty array.

The other larger problem is this line:

@foreach($alert as $alert)

You should use two different variable names here, because each iteration of the loop will assign something to $alert, which will override the first array if they're named the same. The typical and easy fix would simply be:

@foreach($alerts as $alert)

Now they won't override each other.

You also have this part of the method chaining: ->whereNull('deleted_at'). If you use soft deletion, you actually don't have to do this, because Laravel will sort out deleted ("trashed") items for your automatically. (But if you don't use soft deletion, you can ignore this paragraph.)

And Blade's @foreach actually works on Eloquent collections out of the box. So your code can be cleaned up quite a lot, like this:

public function __construct() { 
    $alerts = Alert::orderBy('id', 'DESC')->whereNull('deleted_at')->get();
    return View::share('alerts', $alerts);
}

[...]

@foreach($alerts as $alert)
<div class="alert alert-{{ $alert->type }}" role="alert">{{ $alert->message }}</div>
@endforeach

Upvotes: 3

Related Questions