【问题标题】:Laravel 5.2 Auth relationshipLaravel 5.2 认证关系
【发布时间】:2016-06-23 08:28:18
【问题描述】:

我在使用 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

用户模型:

<?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');
    }
}

产品控制器:

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');
    }
}

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.2


    【解决方案1】:

    我认为用户没有登录这就是为什么 Auth::user() 为空

    【讨论】:

    • 你在正确的地方我把我的路线放在错误的地方谢谢你的欢呼
    【解决方案2】:

    Auth::user() 仅在用户登录时返回 User 对象。您应该添加一些检查代码,例如:

    if (! Auth::check()) {
        // redirect to the login page, etc.
    }
    

    防止它为空。

    【讨论】:

    • 如何在路由中添加 Auth 检查
    • 别担心,我知道它是 'middleware' => 'auth'
    猜你喜欢
    • 2017-01-08
    • 1970-01-01
    • 2016-06-11
    • 2016-08-29
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-11-01
    相关资源
    最近更新 更多