Home > Back-end >  New to Laravel, why is $car not getting passed to my search view?
New to Laravel, why is $car not getting passed to my search view?

Time:12-29

When I dd($car) in my search page, it shows up as this: Image

Route:

Route::get('/search', [RepairController::class, 'search']);

Controller:

public function search(Car $car, Repair $repairs)
    {
        $repairs_new = DB::table('repairs')->where('car_id', '=', $car->id)->get();

        return view('cars.search',
            [   'car' => $car,
                'repairs_new' => $repairs_new]
        );
    }

If you need any additional information to solve this let me know in the comments, thank you.

EDIT (more code changes):

Search form:

<form  type="get" action="/search/{car}">
  <input
    
    type="search" name="query" placeholder="Search repairs">
  <button
    
    type="submit">Search</button>
</form>

The route:

 Route::get('/search/{car}', [RepairController::class, 'search']);

The search function in controller:

public function search(Car $car, Repair $repairs)
    {
        $search_text = $_GET['query'];
        // $repairs = $car->repairs()->get();
        // $repairs_new = $repairs->where($repairs->car_id, '=', $car->id)->get();
        $repairs_new = $repairs->where('repair', 'LIKE', '%' . $search_text . '%')->where('car_id', 'LIKE', $car->id)->get();
        // $repairs_new = DB::table('repairs')->where('car_id', '=', $car->id)->get();

        return view('cars.search',
            [   'car' => $car,
                'repairs_new' => $repairs_new]
        );
    }

CodePudding user response:

As per the documentation, you need to specify how you retrieve the information in the route.

Route::get('/search/{car:id?}/{repairs:id?}', [RepairController::class, 'search']);

Where :id is the database column used to do the lookup. So in this case you'd visit /search/1/1 where 1 is the id for the Car and Repairs record.

Note: ? at the end of the slug is optional here.

Not entirely sure why you're using the DB facade when you can easily use relationships here and do something as simple as $car->repairs() to get the Repairs and just simply pass in the Car model to the search.

  • Related