Laravel 5.2检索经过身份验证的用户ID

时间:2016-02-26 00:23:43

标签: php laravel-5.2

我在Laravel 5.2上遇到一个小问题

我正在尝试检索经过身份验证的用户ID,但由于某种原因无效。每次我的数据库中有0而不是有效的用户ID ...

在我的控制器中,我使用了Auth,在顶部包含。

我的商店方法如下:

public function store(StoreClassifiedRequest $request)
{
    $title = $request->input('title');
    $category_id = $request->input('category_id');
    $description = $request->input('description');
    $price = $request->input('price');
    $condition = $request->input('condition');
    $main_image = $request->file('main_image');
    $location = $request->input('location');
    $email = $request->input('email');
    $phone = $request->input('phone');
    $owner_id = Auth::user()->id;

    ....

    // Create command
    $command = new StoreClassifiedCommand($title, $category_id, $description, $main_image_filename, $price, $condition, $location, $email, $phone, $owner_id);
    $this->dispatch($command);

    return \Redirect::route('classifieds.index')->with('message', 'Listing Created');
  }

一切似乎都没问题,因为插入后id因某种原因总是为0。我在Auth :: user() - > id上做了一个var_dump,我得到了int(2)

我真的很感激任何建议......

StoreClassifiedCommand.php:

<?php

namespace App\Commands;

use App\Commands\Command;
use Illuminate\Contracts\Bus\SelfHandling;
use App\Classified;

class StoreClassifiedCommand extends Command implements SelfHandling {
  public $title;
  public $category_id;
  public $description;
  public $main_image;
  public $price;
  public $condition;
  public $location;
  public $email;
  public $phone;
  public $owner_id;

  // Create a new command instance

  public function __construct($title, $category_id, $description, $main_image, $price, $condition, $location, $email, $phone, $owner_id)
  {
    $this->title = $title;
    $this->category_id = $category_id;
    $this->description = $description;
    $this->main_image = $main_image;
    $this->price = $price;
    $this->condition = $condition;
    $this->location = $location;
    $this->email = $email;
    $this->phone = $phone;
    $this->owner_id = $owner_id;
  }

  //Execute the command.

  public function handle()
  {
    return Classified::create([
      'title' => $this->title,
      'category_id' => $this->category_id,
      'description' => $this->description,
      'main_image' => $this->main_image,
      'price' => $this->price,
      'condition' => $this->condition,
      'location' => $this->location,
      'email' => $this->email,
      'phone' =>$this->phone,
      'owner_id' =>$this->owner_id,
    ]);
  }
}

2 个答案:

答案 0 :(得分:0)

尝试

$request->user()->id;

我不熟悉您提供的代码,但这是猜测。

也可以使用这些。

use Illuminate\Http\Request;
use App\Http\Requests;

以便使用请求对象。

很抱歉,如果我在这里无球状态。

答案 1 :(得分:0)

问题已经解决了,感谢@lagbox。

我没有将$ owner_id设置为我的模型中的错误。我认为这个话题是封闭的。