user9278936
user9278936

Reputation:

laravel 404 error page , redirect

looking for some help, I'm fetching a survey and questions, from method, when select some survey by id, from a route. But when I delete a survey, and when writing in url like http://localhost/survey_details/27 ( 27 is survey Id , which not exist anymore), I'm getting not some expection or redirection or Page not found info, but getting error where undefined variable $dat. But I need some how to show 404 page not found, or just redirect to other page if id not exist. Can some one help me? here is my route:

Route::get('survey_draft/{id}', 'SurveyController@editSurveyDraft');

Here is my controller:

public function viewSurvey($id)
{

    $object = DB::table('question')
        ->where('survey_id', '=', $id)
        ->where('name', '!=', NULL)
        ->get();

    $teamName = DB::table('survey')->where('surveyId', '=', $id)
        ->join('team', 'survey.teamId', '=', 'team.teamId')
        ->join('company', 'company.id', '=', 'team.companyID')
        ->get();

    $company = Auth::user()->company;

    $data = Survey::where('surveyId', '=', $id)->get();
    $teams = Auth::user()->teams;

    $checkUserTeam = DB::table('teammembersall')
        ->where('UserId', '=', Auth::user()->id)
        ->get();

    $members = Survey::where('surveyId', '=', $id)
        ->join('team', 'team.teamId', '=', 'survey.teamId')
        ->join('teammembersall', 'teammembersall.TeamId', '=', 'team.TeamId')
        ->join('users', 'users.id', '=', 'teammembersall.UserId')
        ->select('users.*')
        ->whereNotExists(function ($query) use ($id) {
            $query->select(DB::raw(1))
                ->from('answer')
                ->whereRaw('answer.answerAboutUserId = users.id')
                ->where('answer.surveyId', '=', $id)
                ->where('answer.member_id', '=', Auth::user()->id);
        })
        ->get();

    $questions = DB::table('answer')->get();

    return view('survey_details', ['object' => $object, 'data' => $data, 'teams' => $teams, 'members' => $members, 'questions' => $questions, 'checkUserTeam' => $checkUserTeam, 'teamName' => $teamName, 'company' => $company]);
}

Upvotes: 0

Views: 2103

Answers (1)

Tarek Adam
Tarek Adam

Reputation: 3535

To solve your immediate issue, you could add one of these this after $object ... get() depending on your result. One of them should work.

if(empty($object)){ abort(404); }

or

if(!$object->count()){ abort(404); }

However, your code would be much simpler if you used 2 basic laravel technologies.

  1. ORM instead of DB::...
  2. Route model binding. (which would handle your 404 for you)

https://laravel.com/docs/5.6/eloquent

https://laravel.com/docs/5.6/routing#route-model-binding

Upvotes: 2

Related Questions