Laravel: 查找当前用户的帖子
Laravel: find posts from current user
我克隆了这个示例应用程序:https://github.com/codekerala/laravel-and-vue.js-spa-Recipe-Box
在 RecipeController 中有一个索引函数 returns 所有帖子(或本例中的食谱)。我只需要获取当前登录用户添加的食谱。
public function index()
{
$currentuser = Auth::id();
$recipes = Recipe::where('user_id', '=', $currentuser)
->get(['id', 'name', 'image']);
return response()
->json([
'recipes' => $recipes
]);
}
尝试此操作时,我的 recipes
数组为空,但据我所知没有其他错误。我可以硬编码值 1
而不是 $currentuser
并且它 returns 用户 # 1.
制作的所有食谱
我正在声明 use Auth;
,但我是 Laravel 框架的新手,也许有人可以提供任何帮助?
使用Laravel 5.4.15
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
]);
}
我认为您当前的用户有问题。您无法检索用户 ID
只需使用此语句即可。
$current_user = \Auth::user()->id;
我克隆了这个示例应用程序:https://github.com/codekerala/laravel-and-vue.js-spa-Recipe-Box
在 RecipeController 中有一个索引函数 returns 所有帖子(或本例中的食谱)。我只需要获取当前登录用户添加的食谱。
public function index()
{
$currentuser = Auth::id();
$recipes = Recipe::where('user_id', '=', $currentuser)
->get(['id', 'name', 'image']);
return response()
->json([
'recipes' => $recipes
]);
}
尝试此操作时,我的 recipes
数组为空,但据我所知没有其他错误。我可以硬编码值 1
而不是 $currentuser
并且它 returns 用户 # 1.
我正在声明 use Auth;
,但我是 Laravel 框架的新手,也许有人可以提供任何帮助?
使用Laravel 5.4.15
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
]);
}
我认为您当前的用户有问题。您无法检索用户 ID 只需使用此语句即可。
$current_user = \Auth::user()->id;