Reputation: 149
Hi everyone
I've a question, and it's about Try - Catch, I've a function where I've 3 variables, from two differents models. The problem is, when the model don't have any records in DB, I try redirect the user from the home page, but dind't work, !important, one function had a request for an ajax function inside the view; here my code:
This one is with 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');
}
I used also and IF and ELSE, like this one:
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');
}
}
But didn't work to, if someone can help me, I'll be really gratefull!
Upvotes: 1
Views: 864
Reputation: 11083
You can use the count
method of the collections like this :
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');
}
}
For the try catch
it will not work because there no exception to catch here except if you throw one using the count
method one more time like this
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');
}
Upvotes: 1
Reputation: 534
You could use if(count($events)>0) instead of if($events) . then your else contion will work.
Upvotes: 1