0
votes

I want to implement a search option for some data in my Laravel app, but I have some problems with this:

public function index()
{

     $students= Student::all(); // When I use this form it appear all of Students even I put a name in Search option
     $students= new Student;//When I use this form I have this error: Trying to get property 'name' of non-object ...

    if (request()->filled('name')) {

       $students->where('name', '=', request()->input('name'));         
   }
    else{
           $students=Student::all();
    }
    return view('students.index',['students'=>$students]);
}

And my view is:

 <form action="{{action('StudentController@index')}}" class="d-flex w-100">
                <div class="col-4 p-0">
                    <input class="form-control" type="text" name="name" id="name" placeholder="name">
                </div>
 </form>

When I try to display students' names, I get the error "Trying to get property 'name' of non-object"

2
What do you mean with search option... Dropdown or autocomplete?Sajid Latif
If its autocomplete, you can use this link: w3path.com/…Sajid Latif
I updated my question, I added an image so it is clear now I thinkTriarta AV

2 Answers

1
votes

Students::all() will return a collection of all students, new Student will return an empty model. Neither of these are what you want. Try this instead:

public function index()
{
    $request = request();
    if ($request->filled('name')) {
       // return a collection of students filtered by name
       $students = Student::where('name', $request->name)->get();         
    } else {
       // return a collection of all students
       $students = Student::all();
    }
    return view('students.index', compact('students'));
}
1
votes

In your code below:

$students->where('name', '=', request()->input('name'));         

You're not actually assigning the result of this query to anything. You can do it this way:

return App\Student::where('name', request()->input('name'))->get();

Or

$students = App\Student::where('name', '=', request()->input('name'))->get()

and then later return students in your function (if you do it the 2nd way)

The answer is that the result of your matching query isn't being assigned to the value you think you're returning.

Also, I don't know if there's a reason behind it but you don't need to store all the students in a variable and then query it. You can query the model directly by using it as seen in my examples above.