Laravel:查找当前用户的帖子

时间:2018-03-22 17:46:00

标签: laravel laravel-5.4

我克隆了这个示例应用:https://github.com/codekerala/laravel-and-vue.js-spa-Recipe-Box

在RecipeController中有一个索引函数可以返回所有帖子(或者在这种情况下是食谱)。我只需要获取当前登录用户添加的食谱。

public function index()
  {
      $currentuser = Auth::id();
      $recipes = Recipe::where('user_id', '=', $currentuser)
                 ->get(['id', 'name', 'image']);

      return response()
        ->json([
          'recipes' => $recipes
        ]);
  }

尝试此操作时,我的recipes数组为空,但没有其他错误。我可以硬编码值1而不是$currentuser,它会返回用户#1生成的所有食谱。

我宣布use Auth;,但我是Laravel框架的新手,也许有人可以提供任何帮助?

使用Laravel 5.4.15

2 个答案:

答案 0 :(得分:1)

Auth::user()可能有任何问题请检查。 在控制器中添加以下内容

use Illuminate\Support\Facades\Auth;

添加构造函数

public function __construct()
{
    $this->middleware('auth');
}

public function index()
  {
      $currentuser = Auth::user();
      dump($currentuser);
      $recipes = Recipe::where('user_id', '=', $currentuser->id)
                 ->get(['id', 'name', 'image']);

      return response()
        ->json([
          'recipes' => $recipes
        ]);
  }

答案 1 :(得分:0)

我认为您当前的用户存在问题。您无法检索用户ID 请使用此声明。

$ current_user = \ Auth :: user() - > id;