在我的 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
方法一起使用。我怎样才能在这里正确捕获错误并进行重定向?
我正在使用以下版本:
任何帮助将不胜感激!
要修复错误,请在调用
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()
来检索第一条记录,如果没有记录则抛出异常被发现了。