Ad

Trying To Get Property Of Non-object When Trying To Get ID In Laravel

- 1 answer

I want to make leave application, where the boss can accept or reject leave request

My table in database like this

id |    name     |      email           | person_in_charge |
1      Michael        michael.com                2
2      Johan          johan.com                  4
3      Lorem          lorem.com                  2
4      Ipsum          ipsum.com                  5
5      Dolor          dolor.com

I want to, if user id 5 login, he can view all the request. If user id 2 login, he can view leave request from user id 1 and 3. If user id 4 login, he can view leave request from user id 2, user id 1 and user id 3.

I've doing using while looping, but I have error message "Trying to get property of non-object "

Here's the code

    $id='5';

    $query= Users::where('id',$id)->first();

    if($query->pic_for==null)
    {
        $query = Users::where('pic_for',$id)->first();
        $pic_for = $query->id;

        $pic=array($query->id);
        while($pic_for!=null)
        {
            $query2 = Users::where('pic_for',$pic_for)->first();
            //dd($query2);
            if($query2->pic_for==null)
            {
                break;
            }else
            {
                $pic[]=$query2->id;
                $pic_for = $query2->id;
            }

        }
        dd($pic);
    }

Do you know where I missed ?

Thank you

Ad

Answer

I would try that :

// prepare an empty $result collection that will store the ids of the users
$result = collect();

// probably a number, not a string, in your database: we should keep the right type
$id = 5;
addRelatedUsersToResult($id, &$result);

dd($result);

// add all the related users ids to the result 
// and call itself for each realted user (to check their relations)
function addRelatedUsersToResult($id, &$result) {
    $relatedUsers = Users::where('pic_for', $id)->get();

    // add the related users and checks their children
    foreach ($relatedUsers as $relatedUser) {
        $result->push($relatedUser->id);
        addRelatedUsersToResult($relatedUser->id, $result);
    }    
}
Ad
source: stackoverflow.com
Ad