i am trying to make an add to cart button but there is an error that is happening in this line if (Cart::where('prod_id', $product_id)->where('user_id', Auth::id()->exists())) {
and the error is: Expected type 'object'. Found 'int|string|null'. it is from the Auth::id in the course that i am taking it is not making any error and it is working fine
class CartController extends Controller
{
public function addProduct(Request $request)
{
$product_id = $request->input('product_id');
$product_qty = $request->input('product_qty');
if (Auth::check()) {
$prod_check = Product::where('id', $product_id)->first();
if ($prod_check) {
if (Cart::where('prod_id', $product_id)->where('user_id', Auth::id()->exists())) {
return response()->json(['status' => $prod_check->name . ' Already Added to Cart']);
} else {
$cartitem = new Cart();
$cartitem->prod_id = $product_id;
$cartitem->user_id = Auth::id();
$cartitem->prod_qty = $product_qty;
$cartitem->save();
return response()->json(['status' => $prod_check->name . ' Added to Cart']);
}
}
} else return response()->json(['status' => 'Login to Continue']);
}
}
You are mixing your parenthesis in ->where('user_id', Auth::id()->exists()) section. exists should be outer side of queryBuilder. You should call ->where('user_id', Auth::id()) after that you should chain ->exists().
if (Cart::where('prod_id', $product_id)->where('user_id', Auth::id())->exists()) {
Related
I'm trying to fix an if-else statement in the request for my controller. What I'm trying to do is: if the auth::user-companyID == $request-companyID then true else false; The companyID for the request is in a hidden field on the blade file.
CustomRequest
public function authorize()
{
$user = Auth::user();
if ($user->companyID == $request->companyID) {
return true;
} else {
return false;
}
}
Controller
public function edit(EquipmentRequest $request, $id)
{
$validated = $request->validated();
$user = Auth::user();
$equipment = EquipmentModel::where('id', '=', $id)->first();
$equipment->Year = $request->Year;
$equipment->Make = $request->Make;
$equipment->Model = $request->Model;
$equipment->Type = $request->Type;
$equipment->unitNumber = $request->unitNumber;
$equipment->AnnualInspectionDate = $request->AnnualInspectionDate;
$equipment->userID = $request->userID;
$equipment->companyID = $user->companyID;
$e = $equipment->save();
if ($e) {
$request->session()->flash('success', 'The equipment was successfully updated.');
} else {
$request->session()->flash('error',
'An error occurred while saving. Please refresh your browser and try again.');
}
return redirect()->route('equipmentlist');
}
This form worked before I started messing with it so I know the form is working correctly on the blade file. I'm not sure if you can pass the request data the way I'm doing it or if I have to do a construct to do it this way. I would really appreciate any advice.
use Illuminate\Http\Request;
public function authorize()
{
$user = auth()->user();
return $user->companyID === request()->companyID;
}
I need to capture login user and when i add question i need to save the corresponding user id in the questions table.i'm getting user id when i login but it is not saving in the question table
Controller with store function
public function store(Request $request)
{
//
$last_que = Question::orderBy('question_id', 'desc')->first();
if ($last_que != null) {
$old_queId = $last_que->question_id;
$old_queId = $old_queId + 1;
} else {
$old_queId = 1;
}
$qorder=$request->input('order');
$question=new Question();
$quest=$question->checkDuo($qorder);
if(count($quest)==0)
{
$que=Question::create([
'question'=>$request->input('question'),
'question_id'=>$old_queId,
'question_type'=>$request->input('qtype'),
'question_schedul'=>$request->input('qschedule'),
'created_user_id'=>Session::get('created_id'),
'order_no'=>$request->input('order')
]);
if($que)
{
return redirect()->route('questions.index')->with('success', 'Successfully saved');
}
}
else
{
return redirect()->back()->with('fail', 'Unable to save..! Entry with same order no. already exist');
}
}
in Login index file this is i used capture the user id
<?php
if (!empty($id)) {
Session::put('created_id', $id);
}
?>
Login controller
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user = DB::table('users')->where([['username', '=', $request['username']], ['status', '=', '0']])->first();
$user_id = $user->user_id;
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Get user ID. use something like this.
Auth:user()->id;
Or you can use
Session::getId();
Change this line,
'created_user_id'=>Session::get('created_id'),
To,
'created_user_id'=>Auth::id(),
You used $user_id
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
Than asking:
if (!empty($id)) {
This $id will be always empty so use:
<?php
if (!empty($user_id)) {
Session::put('created_id', $user_id);
}
?>
I have created a wishlist for a shopping cart.So when a non authenticate user wants to see his wishlist after he added to the wishlist. How to show the wishlist based on him before he logged in?
This is my wishlist i have made for only authenticate users:
public function addWish(Request $request)
{
if(Auth::check()){
$name = $request->name;
$product = Product::where('name' , '=', $name)->first();
$product_id = $product->id;
$product = DB::table('wishes')
->where('wishes.product_id','=',$product_id)
->where('wishes.status','=',1)
->select('wishes.product_id')
->first();
if(!$product){
$wish = new Wish();
$wish->user_id =Auth::user()->id;
$name = $request->name;
$product = Product::where('name' , '=', $name)->first();
$wish->product_id = $product->id;
// $product = Product::find($cart->product_id);
$wish->price =$product->price;
$wish->status = 1;
$wish->save();
return redirect('shop-wish');
}
else{
return redirect('shop-wish');
}
}
And this one is for show the list :
public function getWishPage()
{
$id = Auth::user()->id;
$wishList = \DB::table('wishes')
->join('products','wishes.product_id','products.id')
->select('products.feature_image','products.name','products.price as p_price','wishes.id')
->where('wishes.status','=',1)
->where('wishes.user_id','=',$id)
->get();
return view('cart.wishlist',compact('wishList'));
}
But how do i show the non-authenticate users wishlist? Any suggestion or solution would be appreciable?
public function addWish(Request $request)
{
if (Auth::check()){
// ...
} else {
$name = $request->name;
$product = Product::where('name' , '=', $name)->first();
$product_id = $product->id;
if (\Session::has("wishList.$product_id") === true) {
return redirect('shop-wish');
}
\Session::put("wishList.$product_id", $product_id);
return redirect('shop-wish');
}
}
and:
public function getWishPage()
{
if (Auth::check()) {
$wishListId = \Session::get('wishList');
dd($wishListId);
} else {
$id = Auth::user()->id;
$wishList = \DB::table('wishes')
->join('products','wishes.product_id','products.id')
->select('products.feature_image','products.name','products.price as p_price','wishes.id')
->where('wishes.status','=',1)
->where('wishes.user_id','=',$id)
->get();
return view('cart.wishlist',compact('wishList'));
}
}
I want to add a product to my cart But for that i want to logged in the user.Means after he logged in only he can see his cart. But after logged in if he sees the cart, he should see the the product just he added to cart but he saw the old one.Though I put the url on session in controller.How do i make it correct?
Here is show Login form :
public function showLoginForm()
{
Session::put('url.intended',\URL::previous());
return view('cart.login');
}
Add to Cart controller :
public function addCart(Request $request)
{
if(Auth::check())
{
$name = $request->name;
$product = Product::where('name' , '=', $name)->first();
$product_id = $product->id;
$product = DB::table('carts')
->where('carts.product_id','=',$product_id)
->where('carts.status','=',1)
->select('carts.product_id')
->first();
if(!$product){
$cart = new Cart();
$checkBox = Input::get('additionals');
if (is_array($checkBox)){
$cart->additionals = array_sum($checkBox);
}
else {
$cart->additionals =0;
}
$cart->user_id =Auth::user()->id;
$name = $request->name;
$product = Product::where('name' , '=', $name)->first();
$cart->product_id = $product->id;
// $product = Product::find($cart->product_id);
$cart->price =$product->price;
$cart->status = 1;
$cart->save();
return redirect('shop-cart');
}
else {
return redirect('shop-cart');
}
}
else{
return redirect('/login');
}
}
And Login controller :
protected function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (auth()->attempt(array('email' => $request->input('email'),
'password' => $request->input('password'))))
{
if(auth()->user()->is_activated == '0'){
Auth::logout();
return back()->with('warning',"First please active your account.");
}
else{
return Redirect::to(Session::get('url.intended'));
}
}
else{
return back()->with('error','your username and password are wrong.');
}
}
Add to Cart Route:
Route::get('add-to-cart/{name}','CartController#addCart');
public function addcart(Request $request)
{
$id=$request->id; $time=60*24*14; /*60 * 24 * 14 = 14 drays 60=minutes 24=hours 14=days*/
$value=0;
if( Cookie::get('cart')!==null ){
$anonim=Cookie::get('cart');
DB::table("cart")->insert(["anonim"=>$anonim,"product_id"=>$id]);
return 0;
}else{
$value=DB::table("cart")->max("anonim")+1;
if(empty($value)){
$value=0;
}
DB::table("cart")->insert(["anonim"=>$value,"product_id"=>$id]);
$cookie = cookie('cart', $value, $time);
return response()->cookie($cookie);
}
}
I use Laravel5.2 to build a E-commerce platform and get some troubles.When I loginout user state and I use Session::forget('user') or $request->session()->forget('user'), it works in current page,and I redirect to the login page and dd(Session::all()) find the session 'user' still exist!!! so I am confused to know what is wrong with it? plz tell me the reason,thanks all.
ps. loginout code
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
echo json_encode(['result' => 1]);
exit;
}
echo json_encode(['result'=>0,'msg'=>'loginout error']);
exit;
}
The session doesn't get saved until the response is sent and events/middleware are triggered.
Try doing:
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
return Response::json(['result' => 1]);
return '';
}
return Response::json(['result'=>0,'msg'=>'loginout error']);
}
Or if your using the helpers:
public function logout(Request $request)
{
if ($request->session()->has('user')) {
$is_forgotten = $request->session()->forget('user');
if ($is_forgotten === null)
return response()->json(['result' => 1]);
return '';
}
return response()->json(['result'=>0,'msg'=>'loginout error']);
}