user6060368
user6060368

Reputation:

Else Part is not executing even when condition is false Laravel 5.2

I am working on a Web application where i am searching for student result.By entering student roll no i am getting his data from Database.I have Student Model and Students controller , i am getting input from form and field name = keyword . I am comparing $rollno and the keyword it is working perfect but the else part just executes when i enter roll no 0 , without zero whatever i enter it show me the empty view and else part is not executing.

Search function is in Students Controller

public function search()
        {
            $keyword = Input::get('keyword');
            $rollno = Student::find($keyword);
            if($rollno = $keyword){
                return View::make('results.single')
                ->with('search',Student::where('rollno',$keyword)
                ->get())->with('keyword',$keyword);
            }else{
                return 'Nothing Found';
            }
}

Updated :

Thanks to Alex for clearing the question however I changed my search function to the below and it worked perfect.

public function search()
    {
        $keyword = Input::get('keyword');
        $row = Student::where('rollno',$keyword)->first();
        $rollno = $row['rollno'];
        if($keyword == $rollno){
            return View::make('results.single')
            ->with('search',Student::where('rollno',$keyword)
            ->get())->with('keyword',$keyword);
        }else{
            return 'Nothing Found';
        }
    }

Upvotes: 2

Views: 263

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

First, of all, you're trying to compare string with an object. You should add ->keywordRow, just change keywordRow to real one.

Second, use == or === (much better) operator to compare. = is an assignment operator

$keyword = Input::get('keyword');
$rollno = Student::find($keyword)->keywordRow;
if($rollno === $keyword){

Upvotes: 2

Thamilhan
Thamilhan

Reputation: 13313

Your if condition is:

if($rollno = $keyword)

Which means you are assigning $keyword to $rollno. So this is assignment is true. Thus, your if condition always succeeds and your else part has no meaning. You have to use exact comparison operator in if

Upvotes: 0

Related Questions