I would like to make a simple search function for my table. This table get the data from two mssql [Addresses] and [Companies] tables. The tables have one to one relationship.
class Addresses extends Model
{
protected $table = "Addresses";
protected $primaryKey = 'adress';
public $timestamps = false;
public function scopeSearchAddress($query, $searchTerm)
{
return $query->where('city', 'LIKE', '%'.$searchTerm.'%')
->orWhere('name', 'LIKE', '%'.$searchTerm.'%')
->orWhere('street', 'LIKE', '%'.$searchTerm.'%');
}
public function company()
{
return $this->hasOne(Company::class, 'adress');
}
The relationship is one address one company. The first table adress have name, street, city columns and the second table have compName, compType.
class Company extends Model
{
protected $table = "Company";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function addresses()
{
return $this->belongsTo(Addresses::class, 'adress');
}
}
this are the two models. The controller look like this:
class AddressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$addresses = Addresses::whereHas('compan', function($query) {
$query->where('compType','D');
})->orderBy('Name')
->searchAddress($searchTerm)
->paginate(60);
return view('asdress.index', compact('addresses', 'searchTerm'));
}
}
i can search after the first table columns (city, name, street). but how can i search after the second table columns like the compName.
Just add orWhere
for every company table field you want to search on in whereHas
closure.
$searchTerm = $request->input('searchTerm');
$addresses = Addresses::whereHas('company', function($query) use($searchTerm){
$query->where('compType','D')
//append other where queries on company fields
->orWhere('company_table_field_name', $searchTerm);
});