我试图使用Laravel中的多对多关系列出数据库中与特定用户连接的所有产品,但出现此错误:
Undefined variable: products (View: C:\xampp\htdocs\admin\resources\views\welcome.blade.php)
这是我的代码:
Product.php
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = ['file'];
public function users()
{
return $this->belongsToMany(User::class, 'product_user', 'product_id', 'user_id');
}
}
User.php
<?php
namespace App;
use App\Product;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function products()
{
return $this->belongsToMany(Product::class, 'product_user', 'user_id', 'product_id');
}
}
ProductController.php
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
$products = Product::with('users')->get();
return view('welcome', compact('products'));
}
}
welcome.blade.php
@if($products)
<table class="table">
<thead>
<th>#</th>
<th>Product Name</th>
<th>Created At</th>
</thead>
<tbody>
@foreach ($products as $product)
<tr>
<td>{{ $product->id }}</td>
<td>{{ $product->file }}</td>
<td>{{ date('M j, Y', strtotime($product->created_at)) }}</td>
<td>
@foreach ($product->users as $user)
<td>{{ $user->name }}</td>
@endforeach
</td>
</tr>
@endforeach
</tbody>
</table>
@endif
我在网上四处寻找类似的问题,但是我陷于困境,似乎找不到问题,因此,如果有人可以提供一些见解,将不胜感激。