Ad

Fix Error Trying To Get Property Of Non-object Laravel

- 1 answer

I've searched for other questions but couldn't find an answer. I get the following error.

Trying to get property 'nameP' of non-object

Controller

public function store(Request $request)
{
    $hourID = $request->hour_id;
    $id = (Hour::latest()->first()->id) + 1;
    $projectID = $request->project_id;

    $sub = DB::table('hours')->join('projects',
        function ($join) use ($projectID, $id) {
            $join->on('hours.project_id', '=', 'projects.id')
                ->where('hours.project_id', '=', $projectID)
                ->where('hours.id', '=', $id);
        })->select('nameP')
        ->get()->first();

    $name = $sub->nameP;
    $hour = Hour::create([
        'id' => $hourID,
        'project_id' => $request->project_id,
        'day' => $request->day,
        'nHours' => $request->nHours,
        'notesH' => $request->notesH
    ]);

    return Response::json([$hour, 'nameP' => $name]);
}

If I execute this code using Laravel Tinker it works so I don't understand why this error occurs. Any suggestions?

Ad

Answer

You're getting multiple records if you use get() method.

using first() you'll get only one collection.

Remove get(), and use only first() method

$name = '';
$sub = DB::table('hours')->join('projects', function($join) use ($projectID,$id){
                                $join->on('hours.project_id', '=', 'projects.id')
                                ->where('hours.project_id', '=', $projectID)
                                ->where('hours.id', '=', $id);
                            })->select('nameP')->first();
if(!empty($sub)){
    $name=$sub->nameP;
}
Ad
source: stackoverflow.com
Ad