是否有一种方法可以在控制器内设置一个函数来检查某些东西,然后将用户重定向到另一个页面,只是一行 &g



我在控制器中创建了一个函数,它可以检查并在需要时重定向到另一个页面

我想在一行中实现这一点,但不得不采用三行和两个函数来实现。如果有一种方法可以让一个函数同时进行检查和重定向到另一个页面,那将会有所帮助

除了使用中间件之外,我只是在寻找一种更简单的方法来做到这一点,因为我想在不同的控制器中实现其他类型的检查/重定向。我不确定我是否在原始函数中遗漏了什么。如果没有其他方法,我就使用更长的方法或者使用中间件

一开始我想做这样的事情:

public static function redirectIfUserShouldNotSeeOrder(Order $order)
{
if ($order->user_id != auth()->user()->id) {
return redirect()
->route('orders.index')
->with('status', 'You are not authorized to view this order');
}
}
public function order(Order $order)
{
self::redirectIfUserShouldNotSeeOrder($order);
return view('orders.show', compact('order'));
}
public function payPage(Order $order)
{
self::redirectIfUserShouldNotSeeOrder($order);
return view('orders.pay', compact('order'));
}

由于redirectIfUserShouldNotSeeOrder函数返回一个重定向,它在orderpayPage函数中没有做任何事情,页面只是返回他们的视图,跳过先前的重定向

我不得不求助于两种不同的方法:

public static function redirectToOrdersPageAndWarnUser()
{
return redirect()
->route('orders.index')
->with('status', 'You are not authorized to view this order');
}
public static function shouldUserSeeOrder(Order $order)
{
return $order->user_id == auth()->user()->id;
}
public function order(Order $order)
{
if (!self::shouldUserSeeOrder($order)) {
return self::redirectToOrdersPageAndWarnUser($order);
}
return view('orders.show', compact('order'));
}
public function payPage(Order $order)
{
if (!self::shouldUserSeeOrder($order)) {
return self::redirectIfUserShouldNotSeeOrder($order);
}
return view('orders.pay', compact('order'));
}

您应该使用中间件。但这可能对你有帮助

public static function redirectToOrdersPageAndWarnUser()
{
return redirect()
->route('orders.index')
->with('status', 'You are not authorized to view this order');
}
public static function shouldUserSeeOrder(Order $order)
{
return $order->user_id == auth()->user()->id;
}
public static function redirectIfUserShouldNotSeeOrder($order)
{
return static::shouldUserSeeOrder($order) ? null : self::redirectToOrdersPageAndWarnUser();
}
public function order(Order $order)
{
return static::redirectIfUserShouldNotSeeOrder($order)
?? view('orders.show', compact('order'));
}
public function payPage(Order $order)
{
return static::redirectIfUserShouldNotSeeOrder($order)
?? view('orders.pay', compact('order'));
}

相关内容

最新更新