自从我开始我的第一个Laravel项目以来,我一直有错误Trying to get property 'column_name' of non-object
不停,大多数时候我已经能够以某种方式解决它,但问题是,我不知道为什么我得到了错误,或者我该如何防止它。例如,
// 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'));
每当我按下该下载链接时,我都会获得一个带有trying to get property 'column' of non-object (View: /usr/src/workapp/resources/views/pdf/pdfgen.blade.php)
的Whoops页面。为什么我收到此错误而不是打开/保存对话框?
编辑:忘记添加,在尝试获取$ id的特定数据之前,我调用整个表($data = Table::all();
)并在刀片视图中使用@foreach
将其打印在表中
编辑2:添加模型
<?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');
}
}
当你做find($id)
并且记录不存在时,它返回null
。因此,如果您尝试访问任何属性->column
,它将抛出错误。
你可以做findOrFail($id)
或有条件if (is_null($data))
或在前端有$data->column ?? 'defaultvalue
'
现在,第二种情况是您的模型存在但仍然出现错误,请执行以下操作:
$data = Table::find($id);
dd(array_keys($data->toArray()));
如果存在,您应该看到您尝试访问的column
。
最后,如果它不在上面的步骤中但是在表格中,那么检查模型的protected $hidden = []
设置,该设置基本上隐藏了某些列。
之所以发生这种情况,是因为你的qazxsw poi可能是qazxsw poi,而你的$data
记录可能不存在于你的数据库中。
尝试更改您的代码,如下所示:
null
从现在开始,如果您的具有给定id的表不存在,它将自动返回$id
页面。