Reputation: 105
I'm trying to get a student record when the user enters only part of the student's name. In other words, check if one of the current students names contains the string entered by the user, and if so, return that record.
My current code, which return the record only after the user has entered the full name:
public function getStudent($name) {
$std = Student::where('first_name', $name)->get();
return $std;
}
Thanks
Upvotes: 7
Views: 1546
Reputation: 740
Use Like Operator for SQL to Check string in record. refer:https://www.w3schools.com/sql/sql_like.asp
Or use Laravel DB or Eloquent as,
public function getStudent($name) {
$std = Student::where('first_name','LIKE' ,'%'.$name.'%')->get();//Laravel Eloquent
$std = DB::table('student')->where('first_name','LIKE' ,'%'.$name.'%')->get();//DB table method
$std = DB::select("select * from student where first_name LIKE %".$name."%");//DB SELECT method
return $std;
}
Upvotes: 1
Reputation: 15296
The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.
There are two wildcards often used in conjunction with the LIKE operator:
%
- The percent sign represents zero, one, or multiple characters
_
- The underscore represents a single character
Finds any values that have "or" in any position
$students = Student::where('first_name', 'LIKE', '%' . $name. '%')->get();
You can do it as well - whereLike
$students = Student::whereLike('first_name',$name)->get();
Upvotes: 2
Reputation: 2964
Use Like
operator. The LIKE
operator is used in a WHERE clause to search for a specified pattern in a column.
$std = Student::where('first_name', 'like', '%' . $name . '%')->get();
You can visit here for more information
Upvotes: 3
Reputation: 2438
You must to use 'like' to get part of the student's name
$std = Student::where('first_name','like', '%' . $name. '%')->get();
Upvotes: 9
Reputation: 305
You should use the wildcard LIKE
$std = Student::where('first_name','like', '%'.$name.'%')->get();
Upvotes: 2