Henry
Henry

Reputation: 1755

How do I write an @if in Laravel that uses data from my database?

I'm new to Laravel and am using Laravel 6. One of my views is going to contain the values in a row of my MySQL table. The table column is a boolean so it contains either 0 or 1. Rather than displaying 0 or 1 in the view, I want to display YES or NO. An @if seems the logical way to do this but I can't get my @if to work.

@if ({{ $sleepDiaryEntry->outdoorLight }} == 1 )
    <p>Two hours of outdoor light? YES</p>
@else
   <p>Two hours of outdoor light? NO</p>
@endif

I've tried several variations of the @if but every variation gives me a syntax error on the first line of the @if.

Unfortunately, the Laravel manual is very skimpy on details of exactly what arguments can and cannot appear in an @if. They tend to give an example or two and think they've anticipated every possible situation and question.

How I can accomplish what I want to do, either with or without @if?

Upvotes: 0

Views: 68

Answers (3)

ceejayoz
ceejayoz

Reputation: 180004

@if ({{ $sleepDiaryEntry->outdoorLight }} == 1 ) just gets rendered down to:

<?php if ({{ $sleepDiaryEntry->outdoorLight }} == 1 ) { ?>

in the final Blade template, which will cause a syntax error. You don't need the {{ }} tags in the conditional (not just "don't need": they won't be parsed at all here); it takes plain old PHP code in the ().

Upvotes: 1

Ramin eghbalian
Ramin eghbalian

Reputation: 2667

remove {{}} in @if, like followings

@if ($sleepDiaryEntry->outdoorLight == 1 )
    <p>Two hours of outdoor light? YES</p>
@else
   <p>Two hours of outdoor light? NO</p>
@endif

because {{}} for show the variable

Upvotes: 2

J0wZ
J0wZ

Reputation: 61

I am not sure about what you want but by using {{}} you are trying to print data.

Try :

@if ($sleepDiaryEntry->outdoorLight == 1 )
    <p>Two hours of outdoor light? YES</p>
@else
   <p>Two hours of outdoor light? NO</p>
@endif

If it doesn't work:

  • Are you giving $sleepDiaryEntry to the view in your controller method ?
  • Try to {{ dd($sleepDiaryEntry) }} see what you have in your view.

Upvotes: 2

Related Questions