Error : Array to string conversion Laravel

  • 31-05-2022
  • 1863
  • Laravel 9
  • Haresh Chauhan

Array to string conversion !

$data is my payload. Which I want to insert into the database. The attribute wanted to insert into database is name, email, password, post.

The Error Array to string conversion because of post attribute. The post attribute is an array. But the database never accepts array attributes inserted into the database.

Error Example

I am trying to insert this data into the database but the error exception says array to string conversion. Yes, definitely you can see here the post attribute is an array.

So the post attribute can not able to insert into database.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use App\User;

Route::get('/', function () {
        
    $data = [
        'name' => 'Haresh Chauhan',
        'email' => 'haresh@gmail.com',
        'password' => bcrypt('123456'),
        'post' => [
            'title' => 'post title',
            'body' => 'post body'
        ],
    ];

    User::create($data);
});

Possible Solutions

json_encode()

The first solution is, You can covert that array into JSON data. Using json_encode() function.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

use App\User;

Route::get('/', function () {
        
    $data = [
        'name' => 'Haresh Chauhan',
        'email' => 'haresh@gmail.com',
        'password' => bcrypt('123456'),
        'post' => json_encode([
            'title' => 'post title',
            'body' => 'post body'
        ]),
    ];

   User::create($data);
});

Set Attribute In Model

In the model, you can set attribute json_encode().

You can see in the code panel two methods I have to define, One for setAttribute. which will convert the post attribute into JSON and. The second method is getAttribute, this will decode the data.

<?php

namespace App;
    
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
    
class User extends Authenticatable
{
    use Notifiable;
    
    /**
    * The attributes that are mass assignable.
    *
    * @var array
    */

    protected $fillable = [
        'name', 'email', 'password','post'
    ];
    
    /**
    * The attributes that should be hidden for arrays.
    *
    * @var array
    */

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

    /**
    * The attributes that should be cast to native types.
    *
    * @var array
    */

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

    public function setPostAttribute($value)
    {
        return $this->attributes['post'] = json_encode($value);
    }

    public function getPostAttribute($value)
    {
        return json_decode($value);
    }
}

Little Understanding

Whenever you try to access array data as a string that time this error will appear. Especially when you insert data into a database and convert array.

So you can not use an array as a string. Before use, you must need to convert it into serialized data or JSON format.

Thank you for reading our post.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :