dimanche 20 décembre 2020

How to check each row with foreach loop using Laravel

Lets start from a scenario. In my project there are products coming from product table and users as requester are able to request for the product but requester can request a product only one time If requester already requested for the product it will redirect back with error message otherwise the product will add to his request list.

For that i make request table having requester id and product id as foreign key. Here is request controller.The condition only check the first row of the table and not working properly.

Guide me what i am doing wrong??

 public function show($id)
{
    $request_item = new request_item; 
    $loginuser=Auth::user()->id;
    $checkif=DB::select('SELECT * FROM `request`');
    $requester_ID = DB::table('requester')->where('user_id', $loginuser)->value('id');

       foreach ($checkif as $db) 
        {

           if ($requester_ID==$db->requester_id && $id==$db->product_id) {
               
                return redirect()->back()->with('error_code', 5);
            }
            else
            {
                  $requester_ID = DB::table('requester')->where('user_id', $loginuser)->value('id');
                  $request_item->requester_id = $requester_ID;
                  $request_item->product_id = $id;
                  $request_item->save();
                return redirect('myRequest');
                
            }
        }     
        return "Something went wrong! Please try gain later";

      
     
     //return view('myRequest');
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire