1

I have two variables in a controller:

$data = S_core_Country::all();
$cn=\DB::table('s_user_addresses')
   ->join('s_users', 's_users.id', '=', 's_user_addresses.user_id')
   ->join('s_core_countries', 's_core_countries.id', '=', 's_user_addresses.country_id')
   ->value('countryname');                                       

return view('home')->with(['data'=>$data,'cn'=>$cn]);

Is it possible to view my data in foreach loop like this

@foreach($data as $data && $cn as $cn)

If not what should I to show those two variable in one foreach loop?

Mustaque Ahmed
  • 125
  • 1
  • 3
  • 13
  • 2
    it looks like you're joining on the S_users table so you can have all the data available in that $data variable in the $cn variable. In that case you would only have to foreach over $cn – PHP_Developer Dec 12 '18 at 21:27
  • sorry it my mistake.. `$data = S_core_Country::all();` – Mustaque Ahmed Dec 12 '18 at 21:29
  • 2
    you're still joining on that in the query, you should have access in the $cn variable to any data you're looking for. if you wanted to do something like output the country name then all the addresses inside of it, you will just have to look at the location and only output on a new country. – PHP_Developer Dec 12 '18 at 21:34
  • Can you show an example of the output you're trying to produce with this? – Don't Panic Dec 12 '18 at 21:37

2 Answers2

3

For merge and combine array , you can try :

$array = array_merge($array1,$array2);

Example in blade :

@foreach(array_merge($array1,$array2) as $item)
    // ...
@endforeach

Another Example :

@foreach($array1 as $key => $row)
    <li>
        <b>{{ $row['id'] }}</b>
        <p>{{ $array2[$key]->payment }}</p>
    </li>
@endforeach

Related Links :


The && operator(and) is a logical operator.

$a && $b And TRUE if both $a and $b are TRUE.

Max Base
  • 639
  • 1
  • 7
  • 15
0

That foreach is not valid PHP or Blade Syntax unfortunately.

What I would do, to get the most out of the Laravel framework is make a relationship between the user, the address and the country using Eloquent ORM. Then in your blade template you should be able to do something like this:

if $data contains users:

@foreach($data as $user)
  $user->address->country->countryname
@endforeach

Of course this relies on you having the relationship defined in your User, Country & Address models.

An example of what your UserModel might contain:

public function address()
{
  return $this->hasOne('UserAddress', 'foreign_key', 'local_key');
}

The above code is only an example and you'll obviously need to replace it with your correct values. Refer to the Laravel Documentation on Relationships but I definitely think setting up proper ORM relationships would be the way to go here, at least that's what I'd do.

Matthew Brown
  • 4,876
  • 3
  • 18
  • 21