1

I made my custom search for my small car project and I have two problems now. Let me first show my code: This is my SearchController :

<?php

namespace App\Http\Controllers;
use App\Car;
use DB;

use Illuminate\Http\Request;

class SearchController extends Controller
{

    // ovo je search controller


    public function index(){
        $cars = Car::all();
        return view('searchcreate')->with('cars', $cars);
    }

    public function blogs(Request $request){

        $from = $request->input('from');
        $to = $request->input('to');
        $search = $request->input('fuel');

        $cars = DB::table('cars')
                    ->where('brand', '=', $request->input('brand'))
                    ->where('model', '=', $request->input('model'))
                    ->where('fuel', '=', $request->input('fuel'))
                    ->where('gear', '=', $request->input('gear'))
                    ->whereBetween('price', [$from, $to])
                    ->get();

        return view('search')->with('cars', $cars);
    }
}

And this is my search page:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Search</div>

                <div class="card-body">
                    {!! Form::open(['action' => 'SearchController@blogs', 'method' => 'GET']) !!}
                        <div class="column">
                            <label for="name">Brand:</label></br>
                                <select class="form-control" name="brand" id="input" onchange="random_function()">                                 
                                    <option value="" selected>Select your option</option>
                                    <option value="Volkswagen">Volkswagen</option>
                                    <option value="BMW">BMW</option>
                                    <option value="Audi">Audi</option>                                                                   
                                </select>
                        </div>
                        <br>
                        <div class="column">
                            <label for="model">Model:</label></br>
                            <select class="form-control" id="output" name="model">

                            </select>
                        </div>
                        <br>
                        <div class="column">
                            <label for="fuel">Fuel:</label></br>
                            <select class="form-control" name="fuel">
                                <option value="" disabled selected>Select your option</option>
                                <option value="diesel">Diesel</option>
                                <option value="gasoline">Gasoline</option>
                            </select>
                        </div>
<br>
                        <div class="column">
                            <label for="gear">Gear:</label></br>
                            <input name="gear[]" type="checkbox" placeholder="" value="ABS">ABS
                            <input name="gear[]" type="checkbox" placeholder="" value="CL">Child lock
                            <input name="gear[]" type="checkbox" placeholder="" value="navigation">Navigation
                            <input name="gear[]" type="checkbox" placeholder="" value="isofix">Isofix
                        </div>
                        <br>
                        <div class="column">
                            <label for="from">Price from:</label></br>
                            <input name="from" type="text" placeholder="" class="form-control" value="0">
                        </div>
                        <br>
                        <div class="column">
                            <label for="to">Price to:</label></br>
                            <input name="to" type="text" placeholder="" class="form-control" value="150000">
                        </div>
                        <br>

                        <button type="submit" class="btn btn-primary">
                            Search
                        </button>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

So my two problems are:

First problem is that all my search inputs are required, I need if user type just brand or just fuel to show him all cars with that specific brand or fuel.

Second problem is my gear input, it is an array that users select when creating car post. And right now if user want to search for some car with for example just ABS while searching user needs to check exactly gear that car post have. I need my search to find any car post with only checked gear, so no need to check exactly gear. What is solution to these two problems?

EDITED: My cars migration:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCarsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('brand');
            $table->string('model');
            $table->string('fuel');
            $table->string('gear');
            $table->string('price');
            $table->integer('user_id');
            $table->dateTime('refresh');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('cars');
    }
}

My CarsController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Car;
use DB;
use Carbon\Carbon;

class CarsController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $cars = Car::orderBy('refresh', 'desc')->get();
        return view('cars.index')->with('cars', $cars);    
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('cars.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'brand' => 'required',
            'model' => 'required',
            'fuel' => 'required',
            'gear' => 'required',
            'price' => 'required'
        ]);

        $car = new Car;
        $car->brand = $request->input('brand');
        $car->model = $request->input('model');
        $car->fuel = $request->input('fuel');
        $car->gear = implode(',', $request->input('gear'));
        $car->price = $request->input('price');
        $car->user_id = auth()->user()->id;
        $car->refresh = Carbon::now();
        $car->save();

        return redirect('/cars');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $car = Car::find($id);
        return view('cars.show')->with('car', $car);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $car = Car::find($id);
        return view('cars.edit')->with('car', $car);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'brand' => 'required',
            'model' => 'required',
            'fuel' => 'required',
            'gear' => 'required',
            'price' => 'required'
        ]);

        $car = Car::find($id);
        $car->brand = $request->input('brand');
        $car->model = $request->input('model');
        $car->fuel = $request->input('fuel');
        $car->gear = implode(',', $request->input('gear'));
        $car->price = $request->input('price');
        $car->user_id = auth()->user()->id;
        $car->save();

        return redirect('/cars');

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $car = Car::find($id);
        $car->delete();
        return redirect('/cars');
    }

And my create.blade.php for cars table:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Create car post
                </div>

                <div class="card-body">
                    {!! Form::open(['action' => 'CarsController@store', 'method' => 'POST']) !!}
                        <div class="column">
                            <label for="brand">Brand:</label></br>
                            <select class="form-control" id="input" name="brand" onchange="random_function()">
                                <option value="" disabled selected>Select your option</option>
                                <option value="Volkswagen">Volkswagen</option>
                                <option value="BMW">BMW</option>
                                <option value="Audi">Audi</option>
                            </select>
                        </div>
                        <br>
                        <div class="column">
                            <label for="model">Model:</label></br>
                            <select class="form-control" id="output" name="model">

                            </select>
                        </div>
                        <br>
                        <div class="column">
                            <label for="fuel">Fuel:</label></br>
                            <select class="form-control" name="fuel">
                                <option value="diesel">Diesel</option>
                                <option value="gasoline">Gasoline</option>
                            </select>
                        </div>
                        <br>
                        <div class="column">
                            <label for="gear">Gear:</label></br>
                            <input name="gear[]" type="checkbox" placeholder="" value="ABS">ABS
                            <input name="gear[]" type="checkbox" placeholder="" value="CL">Child lock
                            <input name="gear[]" type="checkbox" placeholder="" value="navigation">Navigation
                            <input name="gear[]" type="checkbox" placeholder="" value="isofix">Isofix
                        </div>
                        <br>
                        <div class="column">
                            <label for="price">Price:</label></br>
                            <input name="price" type="text" placeholder="" class="form-control">
                        </div>
                        <br><br>
                        <button type="submit" class="btn btn-primary">
                            Submit
                        </button>
                    {!! Form::close() !!}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
5
  • What column type is gear, since it is a multiple selection option? Commented Jan 20, 2020 at 0:18
  • @mrhn It is varchar Commented Jan 20, 2020 at 1:44
  • So it is only the search input that is an array? Commented Jan 20, 2020 at 6:14
  • We're here bcs we want to help, but SO isn't a code-writing service ... what have you tried? Commented Jan 20, 2020 at 9:30
  • @yes, search input array and store function that is with implode Commented Jan 20, 2020 at 11:43

1 Answer 1

1

You should split your query up into the individual search parts, as there are 3 different types of where clause that you need - standard where, whereIn (for the gears array) and whereBetween (if a price is set)

This should work:

$carQuery = DB::table('cars');

// standard where fields
foreach ($request->only(['brand', 'model', 'fuel']) as $term => $value) {
    if (empty($value)) {
        continue;
    }
    $carQuery->where($term, $value);
}

// gear is one of gears array values
if ($gears = $request->get('gear')) {
    $carQuery->whereIn('gear', $gears);
}

// between a price from/to the values set
if (
    $from = $request->input('from')
    && $to = $request->input('to')
) {
    $carQuery->whereBetween('price', [$from, $to]);
}

$cars = $carQuery->get();
Sign up to request clarification or add additional context in comments.

6 Comments

Sir now it is working all fine if I just select brand and model, or if I just select price from - to. But with gears it still doesn't show anything if I just select one checkbox.. Please help
So with cars that have more than just one gear selected it doesn't show anything, it just show cars with one gear selected, and I need to show me all cars if my gear selected input for SEARCH
My $car->gear is multiple selection , array. Maybe it is something about that ?
And I have a small error with price, it shows me all cars no matter what price did I type in $from and $to input
What does your cars table data look like?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.