为什么在一个请求中使用“with”和“firstOrFail”方法会在找不到数据时引发错误?

问题描述 投票:0回答:1

在我的 Laravel/Livewire 网站上,我正在尝试处理使用

firstOrFail
方法捕获无效 slug 的情况:

class PointShowPage extends Component
{
    public string $slug;
    public $pointItem;

    public function mount(?string $slug)
    {
        $this->slug = $slug;
    }

    public function render()
    {
        try {
            $this->pointItem = Point
                ::getBySlug($this->slug)
                ->with('creator')
                ->firstOrFail();
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
            request()->session()->flash('error', 'Point Page not found !');
            return $this->redirect(route('home'), navigate: true);
        }
    }
}

我的模型中有一个范围:

public function scopeGetBySlug($query, $slug = null)
{
    return $query->where(with(new Point)->getTable() . '.slug', $slug);
}

但是,我遇到了错误:

在 null 上调用成员函数 with()

似乎我无法将

with
firstOrFail
方法一起使用。我怎样才能在这里正确捕获错误并进行重定向?

我正在使用以下版本:

  • “laravel/框架”:“^10.48.4”
  • “livewire/livewire”:“^3.4.9”
  • “spatie/laravel-honeypot”:“^4.5”

任何帮助将不胜感激!

php laravel laravel-livewire
1个回答
0
投票

要修复错误,请在调用

with()
之前调用
getBySlug()
方法。

public function render()
{
    try {
        $this->pointItem = Point::with('creator')
            ->getBySlug($this->slug)
            ->firstOrFail();
    } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
        request()->session()->flash('error', 'Point Page not found !');
        return $this->redirect(route('home'), navigate: true);
    }
}

这里,在

with('creator')
模型的查询构建器实例上调用
Point
,然后调用
getBySlug($this->slug)
来添加where子句,最后,调用
firstOrFail()
来检索第一条记录,如果没有记录则抛出异常被发现了。

© www.soinside.com 2019 - 2024. All rights reserved.