Ad

Laravel: Selective Drop Down Lists

- 1 answer

So my drop down list works that I HAVE to select both options for it to display a list of hotels based on the criteria selected (Distance and price), but I want to make sure that the user can find all hotels based on just Price, for example. When I do this, no hotels appear and my drop down list doesn't quite work. So how would I exactly implement code that will let the user select all the hotels based on just the ONE criteria.

SearchController.php

public function index(Request $request)
{
    $distances = DB::table('posts')->select('distance')->distinct()->get()->pluck('distance');
    $prices = DB::table('posts')->select('price')->distinct()->get()->pluck('price');

    $post = Post::query();

    if ($request->has('price')) {
        $post->where('price', $request->price);
    }

    if ($request->has('distance')) {
        $post->where('distance', $request->distance);
    }

    return view('Pages.search', [
        'distances' => $distances,
        'prices' => $prices,
        'posts' => $post->get(),
    ]);
}
Ad

Answer

Have you tried using when?

public function index(Request $request)
{
    // Unnecessary select * changed to select only the columns you need.
    $distances = DB::table('posts')->select('distance')->distinct()->get(['distance'])->pluck('distance');
    $prices = DB::table('posts')->select('price')->distinct()->get(['price'])->pluck('price');

    $post = Post::when($request->has('price'), function ($query) use ($request) {
        $query->where('price', $request->price);
    })
    ->when($request->has('distance'), function ($query) use ($request) {{
        $query->where('distance', $request->distance);
    })
    ->get();

    /* php  >= 7.4
    $post = Post::when($request->has('price'), fn($query) => $query->where('price', $request->price))
    ->when($request->has('distance'), fn($query) => $query->where('distance', $request->distance))
    ->get();
    */

    return view('Pages.search', compact('distances', 'prices', 'post');
}
Ad
source: stackoverflow.com
Ad