mardi 29 mai 2018

Laravel if no data from select many to many relation

How to check whether there's data from database or not
My DB looks like this

enter image description here

My user Model

public function monsters()
{
    return $this->belongsToMany('App\Monster')->orderBy('star');
}

My Controller

public function list_monster_user()
{
    //GET USER LOGIN ID
    $id = Auth::user()->id;

    $monster_user = User::find($id);

    //IF DATA IS NOT EMPTY OR USER HAVE MONSTERS
    if(!is_null($monster_user->monsters))
    {
        return 'yes';
    }

    //IF DATA IS EMPTY OR USER DOESNT HAVE ANY MONSTER
    else
    {
        return 'nope';
    }
}

I'm using ajax, so the result will be return to ajax.
I don't get the return I want. I know something's wrong with my if statement.
But I couldn't figure it out.

Aucun commentaire:

Enregistrer un commentaire