【问题标题】:How to fix ErrorException in blade.php in Laravel 5.2如何在 Laravel 5.2 中修复 Blade.php 中的 ErrorException
【发布时间】:2018-06-05 21:00:45
【问题描述】:

需要在我的 laravel 应用程序的 File 表中使用 user_id 打印用户名。这是User 模型和File 模型之间的关系。

文件模型

public function user()
{
    return $this->belongsTo(User::class);
} 

这是刀片文件

@if($files)
    @foreach( $files as $file)
        <div>
            <div>
                <span>
                    {{ $file->user->name }} //line 16
                </span>
            </div>
        </div>
    @endforeach
@endif

控制器

class PfilePDFController extends Controller
{
    public function getPFPDF($id){
        $files = File::where('project_id',$id)->get();
        $pdf = PDF::loadView('pdf.projectfiles',['files'=>$files]);
        return $pdf->stream('projectfiles.pdf');
    }
}

但是得到了这个错误:

ErrorException in bd52d760518dfb36a05daedee198eefcb7b87914.php line 16: Trying to get property of non-object (View: C:\Users\dnk\Desktop\acxian\resources\views\pdf\projectfiles.blade.php)

如何解决这个问题?

【问题讨论】:

  • 对此事一无所知
  • 分享您发送$files的控制器代码?
  • 可能user_id 为空或拥有无效用户id$file-&gt;user 返回null。因此,您正试图从null 获取name
  • 查看我更新的 Controllere 我将使用刀片文件 @user2486 打印 PDF 文件
  • 我赌莱尔特。发生错误是因为由于某种原因,您的文件集合中有一个或多个文件没有相关的user。您可以通过以下方式修复它:{{ $file-&gt;user ? $file-&gt;user-&gt;name : '' }} 或在 php 7+ 上使用空合并运算符:{{ $file-&gt;user-&gt;name ?? '' }}

标签: php laravel laravel-5 relationship blade


【解决方案1】:

可能user_idnull 或有无效用户id$file-&gt;user 返回null。因此,您正试图从 null 中获取名称。

避免这种情况的一个好方法是在您的代码中使用or。例如:

{{ $file->user->name or '-' }}

如果行中的任何信息是null,这将打印-

【讨论】:

    猜你喜欢
    • 2017-10-29
    • 2019-09-27
    • 2017-02-08
    • 2017-03-31
    • 1970-01-01
    • 2016-07-20
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多