问题
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));
}
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.
回答1:
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
}
来源:https://stackoverflow.com/questions/42152529/i-want-to-get-user-id-in-laravel-5-3-controller-with-authuser-id-but-it-cre