laravel if route is null or not existing redirect to other page


laravel if route is null or not existing redirect to other page



i have a route is it possible that when the {id} does not exist it will redirect to a certain page or custom error page? something like if(id=null){return redirect etc..}


Route::get('term/test/{id}', 'ListController@get_term_level');


public function get_term_level($id)
{

// $terms = Term::find($id);
$terms=Term::with('level')->where('id','=',$id)->get();
if(is_null($terms)) {
return redirect()->to('/mypage');
}
else{

return view('term_level.index',compact('terms'));
}

}




3 Answers
3



You may try the following if you don't want to change your current data structure of
view file.


view


public function get_term_level($id)
{
// $terms = Term::find($id);
$terms = Term::with('level')->where('id','=',$id)->get();
if ($terms->count() === 0) {
return redirect()->to('/mypage');
}

return view('term_level.index', compact('terms'));
}





yow this is perfect hahaha got it thanks man..
– Grace
Jul 1 at 14:29





Can be simplified with if(!$terms = Term::.....
– OneLiner
Jul 1 at 16:07


if(!$terms = Term::.....



Inside your method get_term_level you could to the following


get_term_level


public function get_term_level($id)
{
$terms = Term::with('level')->where('id','=',$id)->get();

if($terms->isEmpty()) {
return redirect()->to('/mypage');
}

return view('term_level.index',compact('terms'));
}





not working still showing the page with empty data its not re directing..
– Grace
Jul 1 at 13:58





Sorry, try now.
– DumbAnswersForDumbQuestions
Jul 1 at 14:07





still not working maybe
– Grace
Jul 1 at 14:15





i update my question to see my code
– Grace
Jul 1 at 14:15





Try again. Let me know if it works.
– DumbAnswersForDumbQuestions
Jul 1 at 14:24



You could just have a route that redirects


Route::get('term/test', 'ListController@redirectHereFunction');
Route::get('term/test/{id}', 'ListController@get_term_level');






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to add background colour in existing image using Swift?

Moria Casán

How to make file upload 'Required' in Contact Form 7?