phplaravellaravel-bladedompdflaravel-exceptions

What triggers the "Trying to get property of non-object" error


Since I started with my first Laravel project I've been having the error Trying to get property 'column_name' of non-object nonstop, and most of the time I've been able to fix it one way or another, but the problem is, I have no idea of why I get the error, or how can I prevent it. For example,

// In my controller I have this domPDF function...
public function pdfgen(Request $request, $id) {
        $data = Table::find($id);
        View()->share('data', $data);

        if ($request -> has('download')) {
            $pdf = PDF::loadView('pdf/pdfgen');
            return $pdf ->download('pdfgen.pdf');
        }

        return view('pdf/pdfgen');
}
// In my blade file I have a table calling this column...
<td>{{ $data->column }}</td>

// and this link making the request in the pdfgen function... 
<a class="btn btn-primary" href="{{ route('pdfgen', ['download'=>'pdf']) }}">Download PDF</a>
// And in my routes of web.php...
Route::get('/pdfgen/{id}', array('as' => 'pdfgen', 'uses' => 'PDFController@pdfgen'));

and whenever I press that download link, I get a Whoops page with the trying to get property 'column' of non-object (View: /usr/src/workapp/resources/views/pdf/pdfgen.blade.php). Why am I getting this error and not the open/save dialog?

EDIT: Forgot to add, before trying to get specific data with $id, I called the whole table ($data = Table::all();) and used a @foreach in the blade view to print it in the table

EDIT 2: Adding the model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Table extends Model
{
    protected $table = 'table';
    protected $primaryKey = 'id';
    public $incrementing = false;

    protected $fillable = [
        // all columns are strings, even id
        'id',
        'column',
        'column2',
        'column3',
    ];

    public function table2()
    {
        return $this->hasMany('App\Table2');
    }
}

Solution

  • When you do find($id) and the record is not present, it returns null. So if you try to access any property ->column, it will throw error.

    You can either do findOrFail($id) or have condition if (is_null($data)) or on frontend have $data->column ?? 'defaultvalue '

    Now, the second situation where your model is present but you still get error, do :

    $data = Table::find($id);
    dd(array_keys($data->toArray()));
    

    You should see the column you are trying to access if it is present.

    Lastly, if it is not present in above step but is there in the table, then check for protected $hidden = [] setting of your model which essentially hides certain columns.