laravelでテーブル結合し、詳細画面で表示させたい。
解決したいこと
詳細画面(show.blade.php)で、companiesテーブルにあるcompany_nameを表示させたい。
productsテーブル
companiesテーブル
OS:Mac
laravel9
MySQL
・ネットで検索を行い、試してみましたが解決ができませんでした.
何卒ご教授いただけると幸いです。
show.blade.php
@extends('layouts.app')
@section('content')
@section('content')
@if ($item != null)
<table>
<tr>
<th>id</th>
<th>画像</th>
<th>商品名</th>
<th>値段</th>
<th>メーカー</th>
<th>在庫</th>
<th></th>
</tr>
<tr>
<td>{{$item->id}}</td>
<td>{{$item->image}}</td>
<td>{{$item->name}}</td>
<td>{{$item->price}}</td>
<td>{{$item->company_name}}</td>
<td>{{$item->stock}}</td>
<td>{{$item->comment}}</td>
<td>
<form action="edit/{{$item->id}}" method='GET'>
<input type="submit" value="編集">
</form>
</td>
</tr>
</table>
<div class='return'>
<a href="{{route('index')}}">戻る</a>
</div>
@endif
@endsection
@endsection
@section('footer')
@endsection
KadaiController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Company;
class KadaiController extends Controller
{
//一覧表示
public function index(Request $request)
{
$keyword = $request->input('keyword');
$company = $request->input('company_id');
$query = Company::query();
$query->join('products', function ($query) use ($request){
$query->on('products.company_id', '=', 'companies.id');
});
if(!empty($keyword))
{
$query->where('name', 'LIKE', "%{$keyword}%");
}
if(!empty($company))
{
$query->where('company_name', 'LIKE', $company);
}
$items = $query->orderBy('products.id', 'desc')->paginate(5);
$company_list = Company::all();
$hash = array(
'keyword' => $keyword,
'company' => $company,
'items' => $items,
'company_list' => $company_list,
);
return view('kadai.index')->with($hash);
}
//詳細画面
public function show(Request $request)
{
$item = Product::find($request->id);
return view('kadai/show', compact('item'));
}
}
Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Product extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable =
[
'id',
'image',
'name',
'price',
'company_id',
'stock',
'comment',
];
public function companies(){
return $this->belongsTo('App\Models\Company');
}
}
Company.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
use HasFactory;
public $timestamps = false;
// protected $table = 'companies';
protected $fillable =
[
'company_name',
'id',
];
public function products(){
return $this->HasMany('App\Models\Product');
}
}