简体   繁体   中英

Laravel 5.2 IF Statement Syntax, Change Name based on Value

So, I'm going to moving on from PHP native to Laravel framework. See the code below, it's must be error, but this would tell you what I want. I'm confused to the IF statement in Laravel based my database.

<td>
        {{ 
        @if($book->status==1)
            echo 'Available';
        @elseif($book->status==2)
            echo 'Lost';
        @else
            echo 'Not Available';
        @endif
        }}
</td>

Is that possible to print out the name based on database, example: if the value is 1, then I'll print out 'Lost' on my website? Thank you.

<td>
    @if ($book->status == 1)
        Available
    @elseif ($book->status == 2)
        Lost
    @else
        Not Available
    @endif
</td>

A better place for this would be in the book model itself:

public function getAvailabilityAttribute()
{
    if ($this->status == 1) return 'Available';

    if ($this->status == 2) return 'Lost';

    return 'Not Available';
}

Then you could use it directly in your view:

<td>{{ $book->availability }}</td>

Use like this:

<td>       
    @if($book->status==1)
        {{ 'Available' }}
    @elseif($book->status==2)
        {{ 'Lost' }}
    @else
        {{ 'Not Available' }}
    @endif
</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM