Home > OS >  blade condition for laravel
blade condition for laravel

Time:10-22

i want to create a condition inside a foreach that when no information is found in the database to display a message, but when it does not find anything infos is not displayed. Can someone explain to me where i'm wrong? please

Controller:

public function mycharacters()
    {
        $id = Auth::id();
        $user = Player::where('account_id', $id)->get();

        return view('user.characters')->with('user', $user);
    }

Blade

                <h1 class="text-light">My Characters</h1>
                @foreach ($user as $u)

                @if ($u->name !== "")
                <h1 class="text-light">{{ $u->name }}</h1>
                @else
                <h1 class="text-light">I have not found anything!</h1>
                @endif

                @endforeach

CodePudding user response:

It looks as though you're expecting $user to be empty, so then the foreach has nothing to loop through.

Instead you should either loop through the users or show a message when empty

@forelse ($user as $u)
    <h1 class="text-light">{{ $u->name }}</h1>
@empty
    <h1 class="text-light">I have not found anything!</h1>
@endforelse

The @empty block will render in cases when the variable being looped over is empty.

  • Related