0

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

2
  • How do you know which company belongs to which code? Currently you are trying to displaying a random company for a code, what is the point of this? Commented Oct 27, 2020 at 9:15
  • You did not defin $codes on your controller, how can you get $codes on blade ? Commented Oct 27, 2020 at 9:17

2 Answers 2

3
$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);
 }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.