我想使用Auth :: user()-> id在laravel 5.3控制器中获取用户ID,但会导致错误 [英] I want to get user id in laravel 5.3 controller with Auth::user()->id but it creates error their
问题描述
我创建了一个points
表,那里的用户积分将记入借方贷方.结构如下.
id userid p_add p_less description created_at updated_at
1 9 3000 0 purchased -time- -time-
2 9 0 300 expend -time- -time-
I have created a points
table and there users points will be debited credited. the structure is like following.
id userid p_add p_less description created_at updated_at
1 9 3000 0 purchased -time- -time-
2 9 0 300 expend -time- -time-
我正在使用以下控制器代码.
and I am using following controller code.
public function account_page(){
$points = Points::select(DB::raw("sum(p_add)-sum(p_less) as Total"))->where('user_id', 9)->first();
return view('mop.account-page', array('points'=>$points));
}
因此在名为帐户页面结果的视图页面中可以正确显示.
但是此查询获取的是user_id作为静态值.我要动态地.因此,如果将Auth::user()->id
放在9的位置,即使我在顶部使用use Auth;
也不会显示任何内容.帮我从查询中带有动态user_id的数据库中获取净点数.
so in view page named as account page result is correctly displayed as I want.
But this query is getting user_id as a static value. I want it dynamically. So if I put Auth::user()->id
in the place of 9 nothing is displayed even I have used use Auth;
at top. Help me to get net points from database with dynamic user_id in query.
推荐答案
首先希望您有一个具有主键 id 的 users 表以及与之关联的模式在您的项目中.
尝试先使用use Illuminate\Support\Facades\Auth;
然后
Firstly lets hope you have a users table with the primary key id and a modal associated with it in your project.
Try to use use Illuminate\Support\Facades\Auth;
then
// This will check if user is logged in..
if (Auth::check()) {
$user_id = Auth::user()->id;
$points = Points::select(DB::raw("sum(p_add)-sum(p_less) as Total"))->where('user_id', $user_id)->first();
return view('mop.account-page', array('points'=>$points));
} else {
return redirect('somewhere'); // or return anything you want
}
这篇关于我想使用Auth :: user()-> id在laravel 5.3控制器中获取用户ID,但会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!