I'm having a problem with a relationship through the Users model when using the Auth class. The relationship I think is suppose to be $this->hasMany('App\Product') and also will it return the newly saved id back to a variable through this method. When I try to use Auth::user()->products()->save($product) I get the following error. I'm learning Laravel 5.2 and I don't know how this code should work could some give me some help
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');
}
}
ProductModel:
<?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');
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire