Halnex Halnex - 4 months ago 8
PHP Question

How to convert this short if statement in Laravel into a long one?

I have a short if else statement that I'm having trouble converting into a full one.

The reason is I would like to include some html inside instead of just text.

Auth::user()->likes()->where('status_id', $status->id)->first() ? Auth::user()->likes()->where('status_id', $status->id)->first()->like == 1 ? 'You like this post' : 'Like' : 'Like'


Please note that I am doing this inside a blade template.

Answer

It should translate to:

if(Auth::user()->likes()->where('status_id', $status->id)->first()){
    if(Auth::user()->likes()->where('status_id', $status->id)->first()->like == 1){
        $var = 'You like this post';
    }else{
        $var = 'Like';
    }
}else{
    $var = 'Like';
}

Added $var to save the value, without it it doesn't make much sense.

Also, as it is, you could combine the if constructs via and

if(Auth::user()->likes()->where('status_id', $status->id)->first() 
        && Auth::user()->likes()->where('status_id', $status->id)->first()->like == 1){
    $if = 'You like this post';
}else{
    $if = 'Like';
}