0

I have three models: Country.php,Category.php and Region.php. All these models contains a common field named title in database.

I want to extract the title field from each model and create an array variable, so that I can run it in foreach loop in my view.

What would be the optimal method to do so?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
psudo
  • 1,341
  • 3
  • 24
  • 69
  • `https://laravel.com/docs/6.x/collections#method-pluck` will help you extract `title`. Pluck will give you an array. You can merge the resulting arrays to get the array you want. – user3532758 Feb 09 '20 at 14:45

2 Answers2

0

Went for the union query:

        $opt1 = DB::table('countries')
        ->select('countries.name');

        $opt2 = DB::table('tourcategories')
        ->select('tourcategories.name');

        $opt3 = DB::table('regions')
        ->select('regions.name')
        ->union($opt1)
        ->union($opt2)
        ->get();

        dd($opt3);

If anyone has another optimal method feel free to post.

psudo
  • 1,341
  • 3
  • 24
  • 69
0
// assuming that you have related this models
$counties = County::with(['category','region'])->get();

// And in view
@foreach($counties as $county)
    {{$county->title}}
    {{$county->category->title}}
    {{$county->region->title}}
@endforeach
Militaru
  • 521
  • 5
  • 11