DragonFire
DragonFire

Reputation: 4092

Laravel Not Inserting Json Data Into MySQL

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

Upvotes: 1

Views: 212

Answers (2)

VIKAS KATARIYA
VIKAS KATARIYA

Reputation: 6005

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..

Upvotes: 1

Nikhil G
Nikhil G

Reputation: 2466

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

Upvotes: 4

Related Questions