Hayrulla Melibayev
Hayrulla Melibayev

Reputation: 532

Two array in one foreach Laravel

I have two table the first called codes, and second is company.

Codes table structure:
id| title | desc | company | order

Company table structure:
id| name

Here is code from my controller

 $codes= DB::table('codes')->orderBy('company', 'ASC')->get();
 $company = Company::all();
 return view('codes.index',compact('codes', 'company'));

And here is codes from my view.

 @foreach($codes as $code)
   <tr>
    <td>{{$code->title}}</td>
    <td>{{$code->code}}</td>
    <td>{{$company->name}}</td>  
    <td>{{$code->order}}</td>
   </tr>
  @endforeach

I can not get name of company. How is possible? Thanks for all

Upvotes: 0

Views: 101

Answers (2)

Akbar Rahmanii
Akbar Rahmanii

Reputation: 144

$services = Services::orderBy('company', 'ASC')->with('company')->get();
return view('services.index',compact('services'));

view

@foreach($codes as $code)
   <tr>
    <td>{{$code->title}}</td>
    <td>{{$code->code}}</td>
    <td>{{$code->company->name}}</td>  
    <td>{{$code->order}}</td>
   </tr>
@endforeach

I did not know the names exactly because I wrote them because of that approximation. If the company is defined as id, you can get company information using. You just have to define this model in the service model.

 public function company()
 {
    return $this->belongsTo(Companies::class);
 }

Upvotes: 3

Khalid Khan
Khalid Khan

Reputation: 3185

Replace your view code with this

 @foreach($codes as $key => $code)
   <tr>
    <td>{{$code->title}}</td>
    <td>{{$code->code}}</td>
    <td>{{$company[$key]->name}}</td>  
    <td>{{$code->order}}</td>
   </tr>
  @endforeach

And it'll work

Upvotes: 0

Related Questions