使用Auth类时,我通过Users模型遇到关系问题。我认为这种关系应该是$ this-> hasMany(' App \ Product')并且它还会通过此方法将新保存的id返回给变量。当我尝试使用Auth :: user() - > products() - > save($ product)时出现以下错误。我正在学习Laravel 5.2并且我不知道这些代码应该如何工作可以帮助我一些帮助
FatalErrorException in ProductsController.php line 32:
Call to a member function products() on a non-object
的usermodel:
<?php namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use App\Product;
class User extends Authenticatable
{
use EntrustUserTrait;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function products() {
return $this->hasMany('App\Product');
}
}
产品型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = "products";
protected $fillable = ['category_id', 'user_id', 'supplier_id', 'title', 'price'];
public function user() {
return $this->belongsTo('App\User');
}
}
的ProductsController:
class ProductsController extends Controller
{
public function create() {
$categories = Category::lists('name', 'id')->toArray();
$suppliers = Supplier::lists('company_name', 'id')->toArray();
return view('products.create', compact('suppliers', 'categories'));
}
public function store() {
$product = new Product(Request::all());
$id = Auth::user()->products()->save($product);
return redirect('admin/products');
}
}
答案 0 :(得分:3)
我认为用户没有登录,这就是Auth :: user()为空的原因
答案 1 :(得分:1)
Auth::user()
仅返回User
对象。您应添加一些检查代码,例如:
if (! Auth::check()) {
// redirect to the login page, etc.
}
以防止它为空。