Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to get all country_id from one table country_name from other and display country name in dropdown in laravel

step 1: in route

  Route::get('/findbroker', 'PagesController@findbroker')->name('page.findbroker');
Enter fullscreen mode Exit fullscreen mode

step2: in controller

public function findbroker()
    { 
        $all_country = DB::table('countries')->get();
        $all_countries = DB::table('broker')->pluck('country_id');
        $all_states = DB::table('broker')->pluck('state_id');
        $all_cities = DB::table('broker')->pluck('city_id');
        $country= DB::table('countries')->whereIn('id', $all_countries)->pluck('country_name','id',);
        $state= DB::table('states')->whereIn('id', $all_states)->pluck('state_name','id');
        $city=DB::table('cities')->whereIn('id', $all_cities)->pluck('city_name','id');

        $searchbroker=DB::table('broker')->leftJoin('states', 'broker.state_id', '=', 'states.id')->leftJoin('cities', 'broker.city_id', '=', 'cities.id')->leftJoin('countries', 'broker.country_id', '=', 'countries.id')
       ->take(9)
        ->get();

        return view('frontend.findbroker', compact('country','state','city','all_country','searchbroker'));  
    }
Enter fullscreen mode Exit fullscreen mode

Image description

or

public function showDropdown()
    {
        $countryIds = CountryId::pluck('id'); // Retrieve all country IDs from the "country_ids" table

        $countries = Country::whereIn('country_id', $countryIds)->pluck('name'); // Retrieve the country names using the country IDs

        return view('countries.dropdown', ['countries' => $countries]);
    }
Enter fullscreen mode Exit fullscreen mode

Image description

step3: in blade file

<div class="col-md-3">                       
                        <select id="select_country_id" class="selectpicker form-control @error('country_id') is-invalid @enderror" name="country_id" data-live-search="true">
                        <option value="">Select a country</option>
                            @foreach ($country as $id => $country_name)
                                <option value="{{ $id }}">{{ $country_name }}</option>
                            @endforeach
                        </select>
                        @error('country_id')
                        <span class="invalid-tooltip">
                            <strong>{{ $message }}</strong>
                        </span>
                        @enderror
                    </div>
Enter fullscreen mode Exit fullscreen mode

Image description

Another way of filter

Laravel 10.47 to brings new way to filter models

Image description

Top comments (0)