Seeker1337
3 months ago
866
5
Laravel

Laravel 6 Eloquent scope search on multiple fields in one -Where- clause

Posted 3 months ago by Seeker1337

Hello there. Basically I have a search functionality in my website that's working properly but I need to enchance it a little bit.

In short - If I search a vehicle by it's model ( e.g: BMW ) or by it's mark ( e.g: 320 ) it's working. However, I need to modify it to be able to search for both fields in one query ( e.g: BMW 320 ). I tried playing around with the where clause but I can't find the proper syntax.

VehiclesModel.php

class VehiclesModel extends Model
{
    
    protected $table = 'vehicles' ;
    protected $fillable = [
        
      'vehmod', 'vehmark', 'vehyear', 'vehengine', 'vehtrans', 'vehimage', 'vehgalimages' 
        
    ] ;
    
    public function scopeSearch($query, $vehsearch) {
               
        return $query->where('vehmod', 'like', '%' .$vehsearch. '%')
                     ->orWhere('vehmark', 'like', '%' .$vehsearch. '%') 

                     ->orWhere('vehmod', 'like', '%' .$vehsearch. '%' && 'vehmark', 'like', '%' .$vehsearch. '%')  ; // need to modify here
    }

   
}

VehiclesController.php

use App\VehiclesModel ;

class VehiclesController extends Controller
{
    public function index(Request $request)
    {   
        $vehsearch = $request->input('vehsearch') ;
        
        $vehiclesmodel = VehiclesModel::latest()->search($vehsearch)->paginate(30) ;
        
        return view('mypage', compact('vehiclesmodel', 'vehsearch')) ;
    }
}

Please sign in or create an account to participate in this conversation.