1

Please see the code below, can't figure out what is wrong but insert is not happening... any ideas on how to debug/fix

Laravel - Controller

namespace App\Http\Controllers;

use App\Models\PhoneContactsPhonesModel;
use Illuminate\Http\Request;

class CreatePhoneContactsController extends Controller
{
    public function create(Request $request, $id)
    {

        $users = new PhoneContactsPhonesModel;
        $json = dd(json_decode($request->getContent(), true));

        foreach ($json as $key => $value) {

            $users->mysql_user_id = $id;
            $users->phone = $key;
            $users->name = $value;
            $users->save();

        }

    }
}

Laravel - Route

Route::post('create_phone_contacts/{id}', 'CreatePhoneContactsController@create');

Something is wrong with foreach loop - it seems to be working well with hardcoded values outside the loop

6
  • what error is showing? Commented Nov 21, 2019 at 6:18
  • in postman there is no error.. just giving back the array Commented Nov 21, 2019 at 6:19
  • 3
    You're using dd(). That function will dump the value and terminate the execution of the script, so the foreach loop will never be executed.. Commented Nov 21, 2019 at 6:21
  • ok removing dd just inserts only 1 row - which is the last row Commented Nov 21, 2019 at 6:22
  • 2
    That's because you're just updating and saving the same object over and over on each iteration. Are you trying to update existing users or create new ones? Commented Nov 21, 2019 at 6:23

2 Answers 2

4

Remove dd() and create object in for loop. This will solve your issue.

namespace App\Http\Controllers;
use App\Models\PhoneContactsPhonesModel;
use Illuminate\Http\Request;

class CreatePhoneContactsController extends Controller
{
    public function create(Request $request, $id)
    {  
        $json = json_decode($request->getContent(), true);
        foreach ($json as $key => $value) {
            $users = new PhoneContactsPhonesModel;// ---> here
            $users->mysql_user_id = $id;
            $users->phone = $key;
            $users->name = $value;
            $users->save();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

All you have to do is, remove dd() from your code.

Change this

$json = dd(json_decode($request->getContent(), true));  //change here

To this

$json = json_decode($request->getContent(), true); //change this remove dd()

It'll work..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.