Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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

like image 471
moepart Avatar asked Oct 01 '19 10:10

moepart


2 Answers

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

$std = Student::where('first_name','like', '%' . $name. '%')->get();
like image 184
Ryan Nghiem Avatar answered Nov 02 '22 08:11

Ryan Nghiem


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

like image 45
Zain Farooq Avatar answered Nov 02 '22 10:11

Zain Farooq