Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

julianov's avatar

Laravel 9 controller does not save in DB the json

Hello everyone.

I am having problems with storing data in postgresql database.

This is the migration.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ciudadanos', function (Blueprint $table) {
            
            $table->id();
            $table->bigInteger('cuil')->unique();
            $table->string('nombre');
            $table->string('apellido');
            $table->string('email');
            $table->string('password');

            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('confirmed')->default(0);
            $table->string('confirmation_code')->nullable();

            $table->rememberToken();
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('ciudadanos');
    }
};

The php artisan migrate runs ok!

This is the model:

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Ciudadano extends Model 
{
    protected $table = 'ciudadanos';

    protected $fillable =[ 
        'cuil',
        'nombre',
        'apellido',
        'email',
        'password',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

}

The api.php is this:

Route::post('ciudadano', 'App\Http\Controllers\CiudadanoController@store');

and this is the controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Ciudadano;


class CiudadanoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {


        dump($request);

        $this->validate($request, [
            'cuil'=>'required',
            'nombre'=>'required',
            'apellido'=>'required',
            'email'=>'required',
            'password'=>'required',
        ]);
    
        $ciudadano = Ciudadano::create($request->all());
        $ciudadano->save();
        return ("OK");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

The problem is that it does not return "OK" and I can not debug it because console does not show anything.

If I set the return before $ciudadano = Ciudadano::create($request->all()); it returns "OK"

So the problem is with this line Ciudadano::create($request->all()) The client axios is this:

axios({
      method: 'post',
      url: 'http://127.0.0.1:8000/api/ciudadano',
      data: {"cuil":"xxxxx",nombre":"xxx", "apellido":"xxx", "email":"[email protected]", "password":"xxxxx"},
      headers: {
          "Content-Type": "application/json",
          'Access-Control-Allow-Origin' : '*',
          },
    }).then(function (response) { 
           console.log(response)
  });

What can be the problem here?

0 likes
8 replies
MohamedTammam's avatar

Put the column name you want to add into the fillable array in your model.

And it's better return a response.

return response("Ok");

And of course remove dump line if not testing.

1 like
julianov's avatar

@MohamedTammam

but in fillable is what is validated in the controller before save it to database

protected $fillable =[ 
        'cuil',
        'nombre',
        'apellido',
        'email',
        'password',
    ];
rodrigo.pedra's avatar
Level 56

you say console does not show anything. But what is the status code on the network tab? also does the request on the network tab has any response preview?

One bonus tip, the Controller@validated method returns an array with the validated data, so you can avoid calling $request->all() which can bite your feet if you have a loose $fillable property:

public function store(Request $request)
{
    $validated = $this->validate($request, [
        'cuil' => 'required',
        'nombre' => 'required',
        'apellido' => 'required',
        'email' => 'required',
        'password' => 'required',
    ]);

    $ciudadano = Ciudadano::create($validated);
    $ciudadano->save();

    return "OK";
}
1 like
julianov's avatar

@rodrigo.pedra xhr.js:220 POST http://127.0.0.1:8000/api/ciudadano 500 (Internal Server Error) dispatchXhrRequest @ xhr.js:220 xhrAdapter @ xhr.js:16 dispatchRequest @ dispatchRequest.js:58 request @ Axios.js:109 wrap @ bind.js:9 RegisterUser @ Register.tsx:31 buttonHandler @ Register.tsx:24 callCallback @ react-dom.development.js:3945 invokeGuardedCallbackDev @ react-dom.development.js:3994 invokeGuardedCallback @ react-dom.development.js:4056 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4070 executeDispatch @ react-dom.development.js:8243 processDispatchQueueItemsInOrder @ react-dom.development.js:8275 processDispatchQueue @ react-dom.development.js:8288 dispatchEventsForPlugins @ react-dom.development.js:8299 (anonymous) @ react-dom.development.js:8508 batchedEventUpdates$1 @ react-dom.development.js:22396 batchedEventUpdates @ react-dom.development.js:3745 dispatchEventForPluginEventSystem @ react-dom.development.js:8507 attemptToDispatchEvent @ react-dom.development.js:6005 dispatchEvent @ react-dom.development.js:5924 unstable_runWithPriority @ scheduler.development.js:468 runWithPriority$1 @ react-dom.development.js:11276 discreteUpdates$1 @ react-dom.development.js:22413 discreteUpdates @ react-dom.development.js:3756 dispatchDiscreteEvent @ react-dom.development.js:5889 Registro:1 Uncaught (in promise) AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}

rodrigo.pedra's avatar

@julianov so the call errors out for some reason.

Change your JavaScript code to:

axios({
    method: 'post',
    url: 'http://127.0.0.1:8000/api/ciudadano',
    data: {'cuil': 'xxxxx', 'nombre': 'xxx', 'apellido': 'xxx', 'email': '[email protected]', 'password': 'xxxxx'},
    headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
    },
}).then(function (response) {
    console.log(response);
}).catch(function (reason) {
    console.error(reason);
});

So we can see any error messages. And then post the error here.

rodrigo.pedra's avatar

@julianov and please wrap the error output as if it was a code block so we can see the line breaks and parse it easier.

julianov's avatar

@rodrigo.pedra thanks sir you help me. With the browser output I can notices that there was a last migration and the db table had a column that it did not exists

1 like

Please or to participate in this conversation.