【问题标题】:Attempt to read property "produits" on null尝试在 null 上读取属性“产品”
【发布时间】:2021-11-30 15:13:37
【问题描述】:

我想添加到愿望清单;单击添加后,出现错误。我认为我想要访问产品的方式是错误的。

public function addToFavorie($id)
{
    $user = Auth::user();
    $product = produit::find($id);

    if (!$product || !$user) {
        abort(404);
    }

    // I believe this is the part responsible for the error
    $favorie = $user->favorie;
    $favprds = $favorie->produits;
    //

    for ($i = 0; $i < count($favprds); $i++) {
        if ($favprds[$i]->id == $id)
            return redirect()->back()
                ->with('error', 'produit deja dans votre favorie');
    }
    $favorie->produits()->attach($product->id);

    return redirect()->back()->with('info', 'produit ajoute a votre favorie');
}

型号

public function user()
{
    return $this->belongsTo("App\Models\User");
}

public function produits()
{
    return $this->belongsToMany('App\Models\Produit', 'produits_favories');
}

我在控制器中试过这个,它返回 404。

$user = Auth::user()->favorie;
$product = produit::find($id);

if (!$product || !$user) {
    abort(404);
}

$favprds = $favorie->produits;

【问题讨论】:

  • $favorie 为空,所以你需要检查$user-&gt;favorie
  • 对不起,我无法关注,你能告诉我如何检查吗?谢谢
  • 这一行$favorie = $user-&gt;favorie; 没有返回一个对象,所以这一行$favprds = $favorie-&gt;produits; 给出了一个错误
  • $user-&gt;favorie 正在返回null,因此您无法从中获取产品。如果您认为它不应该返回 null,您需要找出它返回 null 的原因,或者在对它执行任何其他操作之前检查 null。

标签: php laravel logic laravel-8


【解决方案1】:

而不是使用“belongsToMany” public function produits() { return $this-&gt;belongsToMany('App\Models\Produit', 'produits_favories'); } 像这样使用“hasMany” public function produits() { return $this-&gt;hasMany('App\Models\Produit', 'produits_favories'); } 它应该工作

【讨论】:

  • 它返回相同的错误,先生,我不知道该怎么做了
【解决方案2】:
public function addToFavorie($id)
{
    $product = produit::findOrFail($id);

    $favorie = Favorie::firstOrCreate([
        'user_id' => auth()->id()
    ], [
        /* attributes for a `Favorie` instance */
    ]);
    $favorie->produits()->syncWithoutDetaching($product->id);

    return redirect()->back()->with('info', 'produit ajoute a votre favorie');
}

【讨论】:

    猜你喜欢
    • 2022-01-04
    • 2021-09-14
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2023-01-26
    • 2021-05-17
    相关资源
    最近更新 更多