简体   繁体   中英

How can I search for a record using a part of a string field in Laravel/Eloquent?

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

You must to use 'like' to get part of the student's name

$std = Student::where('first_name','like', '%' . $name. '%')->get();

You should use the wildcard LIKE

$std = Student::where('first_name','like', '%'.$name.'%')->get();

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(); 

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM