I am trying to add a search form to my application. I thought I had everything right, but Laravel keeps on telling undefined $users in the view.
The Form Below
<form action="{{URL::to('/students')}}" method="post">
@csrf
<div >
<div >
<input type="search" name="search" value="{{old('search')}}" placeholder="Enter Search Term">
<div >
<input type="submit" value="Search Students">
</div>
</div>
<div >
<span >@error('search'){{$message}}@enderror</span>
</div>
</div>
</form>
UsersController
public function search(Request $request){
$request->validate([
'search' => 'required',
]);
$query = Students::SELECT('*')
->where('name','LIKE','%'.$request->search.'%')
->orWhere('email','LIKE','%'.$request->search.'%')
->orWhere('department','LIKE','%'.$request->search.'%')
->orWhere('course','LIKE','%'.$request->search.'%')
->get();
return view('students',['users' => $query]);
}
Routes
Route::get('/students',function(){
return view('students');
}
Route::post('/students',[UsersController::class,'search']);
Inside Students View at views/students.blade.php
<table >
<thead>
<tr>
<th>Student ID</th>
<th>Stdent Name</th>
<th>Student Email</th>
<th>Student Department</th>
<th>Student Course</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->department}}</td>
<td>{{$user->course}}</td>
<td>
</tr>
</tbody>
</table>
It tells me that $users undefined
Can somebody help me solve this issue?
CodePudding user response:
Route::get('/students',[UsersController::class,'view']);
you're existing get route is literally only returning a view and nothing else so of course $users isn't defined
CodePudding user response:
This is how I did it.
public function search(Request $request){
$query = Students::where('name','LIKE','%'.$request->search.'%')->get();
return view('index',['students' => $query]);
}
in the Route
use App\Http\Controllers\StudentController;
Route::get('/',function(){
return view('welcome');
});
Route::get('/'[StudentController::class,'search']);
``
in view at view/welcome.blade.php
It tells me that $students is undefined. How do I pass the variable in the route?
@foreach($students as $student)
{{$tudent->id}}
{{$student->name}}
{{$student->email}}
@endforeach