If value exist in database don't save Laravel - php

I'm creating a wishlist where the user can save his own products and save them. What I want is that a user can't save a product more than one time.
So, what I'm doing is, if the product_id exists in the DB, I don't want to save the new record.
This is my code, what am I doing wrong?
public function addWishlist(Wishlist $wishlist) {
$wishlist->user_id = request('user_id');
$wishlist->product_id = request('product_id');
if(DB::table('wishlists')->where('product_id' !== $wishlist->product_id)) {
$wishlist->save();
return redirect()->back();
}
}

what about this
public function addWishlist(Wishlist $wishlist) {
$userId = request('user_id');
$productId = request('product_id');
$found = Wishlist::where('user_id', $userId)->where('product_id', $productId)->count();
if($found == 0) {
$wishlist->user_id = $userId;
$wishlist->product_id = $productId;
$wishlist->save();
return redirect()->back();
}
}

public function addWishlist(Wishlist $wishlist) {
if(DB::table('wishlists')->where(['user_id'=>$user_id,'product_id'=>$wishlist->product_id])->exists()){
// record already exist
return redirect()->back();
}else{
// record not exist , save the record
$withlist = new Wishlist();
$wishlist->user_id = request('user_id');
$wishlist->product_id = request('product_id');
$wishlist->save();
return redirect()->back();
}
}

You can use firstOrNew and you need to check with user_id and product_id combination
$wishlist::firstOrNew(array('user_id' => request('user_id'),'product_id'=>request('product_id')));
$wishlist->user_id = request('user_id');
$wishlist->product_id = request('product_id');
$wishlist->save();
return redirect()->back();

Have you tried firstOrCreate()
$user = User::firstOrCreate(['email' => $email])

Related

Laravel edit orders as user

I create order system in Laravel, I can add new order as user and I can display all order as admin user. I have only problem with edit this order as user.
This is my controller
public function index(){
$orders = Orders::with('category', 'type')->where('user_id', auth()->user()->id)->orderBy('id', 'desc')->paginate(6);
return view('account.orders', compact('orders'));
}
public function store(Request $request) {
$order = new Orders;
$order->user_id = auth()->user()->id;
$order->category_id = $request->input('category_id');
$order->type_id = $request->input('type_id');
$order->name = $request->input('name');
$order->description = $request->input('description');
$order->price = $request->input('price');
$order->save();
return back()->with([
'status'=> [
'type'=>'success',
'content'=>'Zmiany zostaƂy zapisane',
]
]);
}
public function edit(Orders $order_id){
$categories = Categories::get();
$types = OrdersCategories::get();
$order = Orders::where('user_id', auth()->user()->id)->findOrFail($order_id);
return dd($order_id);
}
When I click edit in user dashboard not show data from database.
Try This,in your controller edit function.
try {
$categories = Categories::get();
$types = OrdersCategories::get();
$order = Orders::where('user_id', auth()->user()->id)
->findOrFail($order_id);
return redirect()->action('Admin\OrderController#index');
} catch (\Exception $exception) {
return back()->withError($exception->getMessage())->withInput();
}
Because your model is called Orders. You should be using /{orders}/ instead of /{order}/ in your routes if you want to make use of route-model binding.
Change the route to Route::get('/{orders}/edit', 'OrderController#edit')->name('edit');

capture user id when login and save user id based on operations

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);
}
?>

How to show non authenticate user data or wishlist

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'));
}
}

How to add to cart or wishlist without Logged in

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);
}
}

callback on code igniter always return false

i am currently making this part that can create something to input to database. i used callback function of code igniter to check availability of some item code of a non auto increment table.
i always get the message of the callback '{field} exists.' how do i fix this?
controllers
// CREATE /////////////////////////////////////////////////////////
public function create(){
$this->load->library('form_validation');
$this->form_validation->set_rules('JOB_CODE','Job Code','trim|required|min_length[2]|max_length[5]|callback_check_if_exists');
$this->form_validation->set_rules('JOB_NAME','Job Name','trim|required|max_length[30]');
if($this->form_validation->run() == FALSE){
$this->add_view();
}else{
$input = array(
'JOB_CODE' => $this->input->post('JOB_CODE'),
'JOB_NAME' => $this->input->post('JOB_NAME')
);
$this->Job_Titles_Model->insert($input);
}
}
/////////// FOR TABLES WITH NO AUTO INREMENT
public function check_if_exists($jobcode){
$this->load->model('Job_Titles_Model');
$availability = $this->Job_Titles_Model->check_if_exists($jobcode);
if($availability){
return TRUE;
}else{
return FALSE;
}
}
models
///// CREATE /////////////////////////////////////////////////////////
public function insert($input){
$insert = $this->db->insert('job_titles',$input);
}
/////////// FOR TABLES WITH NO AUTO INREMENT
public function check_if_exists($jobcode){ //CHECK IF JOBODE IS AVAILABLE
$sql = ('SELECT * FROM job_titles WHERE JOB_CODE = ?');
$data = array('JOB_CODE' => $this->input->post('JOB_CODE'));
if($result->num_rows() == 0){
return TRUE;
}else{
return FALSE;
}
}

Categories