大家好
我有一个问题,它是关于尝试 - 捕获的,我有一个函数,我有 3 个变量,来自两个不同的模型。问题是,当模型在数据库中没有任何记录时,我尝试从主页重定向用户,但不起作用,!重要的是,一个函数在视图中请求了 ajax 函数;这是我的代码:
这个是尝试和捕捉
try
{
$events = Event::all();
$competitions = Competition::orderBy('id', 'DESC')->get();
$ultimos = Event::orderBy('id', 'DESC')->paginate(5);
if ($request->ajax()) {
return Response::json(View::make('events.partials.last', array('ultimos' => $ultimos))->render());
}
return View('events.index', compact('events', 'ultimos', 'competitions'));
} catch (Exception $e) {
return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
}
我也用了IF和ELSE,像这样:
public function show_events(Request $request)
{
$events = Event::all();
if($events) {
$competitions = Competition::orderBy('id', 'DESC')->get();
$ultimos = Event::orderBy('id', 'DESC')->paginate(5);
if ($request->ajax()) {
return Response::json(View::make('events.partials.last', array('ultimos' => $ultimos))->render());
}
return View('events.index', compact('events', 'ultimos', 'competitions'));
} else {
return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
}
}
但是没有工作,如果有人能帮助我,我会非常感激!
你可以像这样使用集合的count
方法:
public function show_events(Request $request)
{
$events = Event::all();
if($events->count() > 0) {
$competitions = Competition::orderBy('id', 'DESC')->get();
$ultimos = Event::orderBy('id', 'DESC')->paginate(5);
if ($request->ajax()) {
return Response::json(View::make('events.partials.last', array('ultimos' => $ultimos))->render());
}
return View('events.index', compact('events', 'ultimos', 'competitions'));
} else {
return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
}
}
对于try catch
,它不起作用,因为这里没有例外可以捕获,除非您使用 count
方法再次像这样抛出一个
try {
$events = Event::all();
if($events->count() > 0) {
throw new Exception("Ha ocurrido un errror, lo sentimos");
}
$competitions = Competition::orderBy('id', 'DESC')->get();
$ultimos = Event::orderBy('id', 'DESC')->paginate(5);
if ($request->ajax()) {
return Response::json(View::make('events.partials.last', array('ultimos' => $ultimos))->render());
}
return View('events.index', compact('events', 'ultimos', 'competitions'));
} catch (Exception $e) {
return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
}
您可以使用 if(count($events(>0( 代替 if($events( 。 那么你的 else contion 将起作用。