大家好
我有一个问题,它是关于Try - Catch,我有一个函数,我有3个变量,来自两个不同的模型。问题是,当模型在DB中没有任何记录时,我尝试从主页重定向用户,但是不行,重要的是,一个函数在视图中请求了ajax函数;在这里我的代码:
这个是Try and Catch
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');
}
}
但没有工作,如果有人可以帮助我,我会非常感激!
答案 0 :(得分:1)
您可以使用if(count($ events)> 0)而不是if($ events)。然后你的其他词就行了。
答案 1 :(得分:1)
您可以使用这样的集合的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');
}