I have controller
public function category(Categories $category)
{
$product_random = DB::table('products')->where('is_active', 1);
$currency = DB::table('currency')->where('id', 1)->get();
if(count($category->children))
{
$categories = Categories::where('parent_id', $category->id)->get();
return view('catalog2', compact('category', 'categories', 'product_random', 'currency', 'category_id'));
}
else
{
$categories = Categories::where('parent_id', null)->get();
$categories_pod = Categories::where('parent_id', $category->id)->get();
$product_s = Product::where('is_active', 1)->get();
$product = product::where('category_id', $category->id)->where('is_active', 1)->get();
if($price = request('individualprice'))
{
$product->orderBy('individualprice', $price);
}
return view('products', compact('category', 'product', 'categories', 'currency', 'product_s','categories_pod'));
}
}
and BLADE
<div>Sort by price descending</div>
<div>Sort by price</div>
Related
Am just learning Laravel and I have this logic were in I want to display array of total items based from user, to explain this further here is my database
user table
items table
this is my current code
public function display()
{
$users = User::where('type', 'Shop')->get();
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
}
$total = Item::where('user_id', $shop_id)->sum('total');
$shops =[
['Name' => $shop_name, 'total' => $total],
];
return response()->json([
"shops" =>$shops
], 200);
}
and here is my sample output:
am only getting 1 object instead of 2 as I have two shops how to loop this dynamically.
thanks
the $shops and $total variable is not in foreach loop that's because it returns only one row. and you must use $shops[] .
public function display()
{
$users = User::where('type', 'Shop')->get();
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
$total = Item::where('user_id', $shop_id)->sum('total');
$shops[] =['Name' => $shop_name, 'total' => $total];
}
return response()->json([
"shops" =>$shops
], 200);
}
but the best and clean way is to use laravel relationship
in User model:
public function items()
{
return $this->hasMany(Item::class) ;
}
and display controller :
public function display()
{
$shops = User::where('type', 'Shop')->get()
->mapWithKeys(function($user){
return ['name'=>$user->name ,
'total'=> $user->items->sum('total')
]});
return response()->json(["shops" =>$shops], 200);
}
Do this
$shops[] = ['Name' => $shop_name, 'total' => $total];
to push all the shops into one array.
You are currently overriding the hole array.
UPDATE: Also move the sql part into the foreach:
foreach($users as $user){
$shop_id = $user['id'];
$shop_name = $user['name'];
$total = Item::where('user_id', $shop_id)->sum('total');
$shops[] =['Name' => $shop_name, 'total' => $total];
}
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()) {
I have two tables: admins and log_doctor_infos. admins table has relationship hasOne with log_doctor_infos throught doctor_id like this.
In model Admin:
public function logDoctorInfo() {
return $this->hasOne(LogDoctorInfo::class, 'doctor_id', 'id');
// Model LogDoctorInfo is log_doctor_infos table
}
And in Model LogDoctorInfo:
public function doctor(){
return $this->belongsTo(Admin::class, 'doctor_id', 'id');
// Model Admin is admins table
}
I get all data form admins table and i want to sort record has relationship with log_doctor_infos to top.
Yellow record, which has relationship with log_doctor_infos and i want to sort it in top.
Edit: i use paginate in this query and i really want to get quantity of Yellow record.
Thanks for reading!
In my controller, i have custom filter and paginate. Help me.
public function index(Request $request) {
$fullname = $request->query('fullname', NULL);
$phone = $request->query('phone', NULL);
$status = $request->query('status', NULL);
$doctors = (new Doctor)->newQuery();
if ($fullname != NULL) {
$doctors = $doctors->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone != NULL) {
$doctors = $doctors->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status != NULL) {
$doctors = $doctors->where('status', $status);
}
$doctors = $doctors
// ->with(array('logDoctorInfo' => function($query) {
// $query->orderBy('updated_at', 'ASC');
// }))
->latest()
->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
you can use the withCount method.
Admin::withCount('logDoctorInfo')
->orderBy('log_doctor_info_count', 'desc')
->paginate(5);
Your controller will look like this
public function index(Request $request) {
$fullname = $request->input('fullname', NULL);
$phone = $request->input('phone', NULL);
$status = $request->input('status', NULL);
$doctorQuery = Doctor::query();
if ($fullname) {
$doctorQuery->where('fullname', 'LIKE', '%'.$fullname.'%');
}
if ($phone) {
$doctorQuery->where('phone', 'LIKE', '%'.$phone.'%');
}
if ($status) {
$doctorQuery->where('status', $status);
}
$doctorQuery->withCount('logDoctorInfo')
->orderBy('log_doctor_info_count');
$doctors = $doctorQuery->paginate()
->appends([
'fullname' => $fullname,
'phone' => $phone,
'status' => $status
]);
// dd($doctors);
return view('admin.doctors.index', compact('doctors'));
}
Doctor::with('logDoctorInfo')->get()->sortByDesc('logDoctorInfo.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);
}
}