Laravel:试图访问null类型值上的数组偏移量



我目前正在销售系统上工作,每个产品将有几个文档(PDF, docs, img, excel),有些可能没有。文档被分组在一个文件夹中,并且构建了按钮供用户下载包含文档的文件夹(zip下载)。用户需要在下载文档文件夹之前先购买产品。

尝试访问null类型值上的数组偏移

当我需要使用下载文档文件夹的按钮访问产品详细信息页面时发生错误。

<<p>产品控制器/strong>
public function specific($id, Product $product)
{
$product = Product::where('type', 2)->findOrFail($id);
$document = Document::where('product_id', $product->id)->first(); //
return view('web.detail', compact('product', 'document'));
}

下面是为了让购买了产品的用户下载文档文件夹而进行的检查。

detail.blade.php

<div>
// check if product has document
@if ( count($product->product_document) > 0 ) 

<div>
<p>You can download the Fact Sheet below by clicking the button below.</p><br>
@auth
@php   
use AppModelsOrder;    
$orders = Order::where([
'member_id' => Auth::user()->profile->member['id'], 
'product_id' => $document->product_id
])->get();
@endphp               

// check if user has purchased the product
@if (count($orders) > 0)
@foreach($orders as $order)
<div class="row">
@if ($order['order_status'] === 3)
{{-- Paid --}}
<div><a href="{!! route('web.download', $product->id) !!}" class="btn-design">
Download</a>
</div>
@else
{{-- Unpaid --}}
<div><a href="{{ route('web.order', $product->id) }}" class="btn-design">
Download</a>
</div>
@endif
</div>
@endforeach
@else
...
@endauth
</div>
@else
<div><p>There is no Fact Sheet for this product yet.</p></div>
@endif
</div>

Product.php

public function product_document()
{
return $this->hasMany(Document::class, 'product_id', 'id');
}

Document.php

public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}

Order.php

public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
public function member()
{
return $this->belongsTo(Member::class, 'member_id');
}

任何帮助将不胜感激!

很难判断错误来自哪里,因为您没有提供堆栈跟踪或特定元素为空。但是,我的猜测是这个拉力可能导致问题:

$orders = Order::where([
'member_id' => Auth::user()->profile->member['id'], 
'product_id' => $document->product_id
])->get();

具体这部分:Auth::user()->profile->member['id']

您的用户可能没有配置文件。在这种情况下,它找不到member['id'],因为有一个空值试图调用数组的值。

或者概要文件没有加载。尝试在调用数组之前加载它:Auth::user()->loadMissing('profile');(loadMissing只是加载关系,如果它还没有加载)

不知道用户的这些值是什么,或者它是如何设置的,这使得它很难,但同样的问题可能适用于member对象——它可能没有设置,或者可能无法加载。

要进行测试,请尝试将user对象转储到不同的级别(只转储user,然后转储profile,然后转储member),并查看返回的结果。这将是一个非常快速的空值指示符。

相关内容

最新更新