Home > Enterprise >  How to make a job to save an object as json in the database in Laravel?
How to make a job to save an object as json in the database in Laravel?

Time:05-09

I'm trying to make a job that saves the HTTP response as json in the database using the handle method, this is my code:

   public function handle()
{
    $syncedResults = $this->guzzleGet();
    Rfm::truncate();
    
    /**
     * @var \Illuminate\Database\Eloquent\Model $rfm
     */
    Rfm::create(['RFM' => $syncedResults]);

 
}

public function guzzleGet()
{
    $aData = [];
    $sCursor = null;

    while($aResponse = $this->guzzleGetData($sCursor))
    {
        if(empty($aResponse['data']))
        {
            break;
        }
        else
        {

            $aData = array_merge($aData, $aResponse['data']);


            if(empty($aResponse['meta']['next_cursor']))
            {
                break;
            }
            else
            {
                $sCursor = $aResponse['meta']['next_cursor'];
            }
        }
    }
    

    
    return json_encode($aData);

here is my model :

<?PHP

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Rfm extends Model
{
use HasFactory;
protected $fillable = ['RFM'];  
}

And the migrations:

   public function up()
{
    Schema::create('rfms', function (Blueprint $table) {
        $table->id();
        $table->json('RFM');
        $table->timestamps();
    });
}

now I made a signature command to run the worker but every time it fail with this error in the log:

TypeError: Illuminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string given, called in C:\xampp\htdocs\clv\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 920 and defined in C:\xampp\htdocs\clv\vendor\laravel\framework\src\Illuminate\Database\Grammar.php:136

i wonder if I'm doing something wrong?!

CodePudding user response:

JSON fields accept array datatype, but you're converting your array into a string before passing it,

So just change the return of guzzleGet() from return json_encode($aData); into return $aData;

CodePudding user response:

i have fixed it in the meanwhile:

just inserting the data using the Query Builder instead of eloquent, Like this:

public function handle()
{
    $syncedResults = $this->guzzleGet();
    Rfm::truncate();
    
    /**
     * @var \Illuminate\Database\Eloquent\Model $rfm
     */
    DB::table('rfms')->insert(['RFM' => json_encode($syncedResults)]);

}
  • Related