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

vainway 's avatar

ErrorException Array to string conversion

hello guys am trying to submit a form to my database and am getting this error ErrorException Array to string conversion

<div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="bmd-label-floating">Class Name/label>
                    <input type="text" wire:model="title" class="form-control @error('title') is-invalid @enderror" placeholder="EX: 1st grade">

                    @error('title')
                        <span class="invalid-feedback" role="alert">
                            <strong>{{ $message }}</strong>
                        </span>
                    @enderror
                </div>
            </div>
        </div>
<div class="current-step">
        <!-- filepond -->
        <div class="row"> 
            <div class="col-md-12">
                <div 

                wire:ignore

                x-data 
                
                x-init="

                FilePond.registerPlugin(FilePondPluginImagePreview);

                FilePond.setOptions({
                    AllowMultiple: 'multiple' ? 'true' : 'false',
                    server: {
                        process: (fieldName, file, metadata, load, error, progress, abort, transfer, options) => {
                            @this.upload('uploadedFiles', file, load, error, progress)
                            
                        },
                        revert: (filename, load) => {
                            @this.removeUpload('uploadedFiles', filename, load)
                        },
                    },
                });

                FilePond.create($refs.input);

                " 
                >
                    <label>File Upload</label>
                    <input type="file" x-ref="input" wire:model="uploadedFiles" multiple>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="bmd-label-floating">Skills required for your project?</label>
                    <div wire:ignore class="bootstrap-tagsinput info-badge">
                        <select wire:model="skills" class="form-control js-select2-multi" data-placeholder="Enter Skills here..." multiple>                            
                            @foreach($skill as $item)
                                <option value="{{ $item->id }}">{{ $item->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
        </div>

        
    </div>

my livewire controller

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Skills;
use App\Models\Post;
use Illuminate\Support\Facades\Auth;

class Post extends Component
{
    use WithFileUploads;

    public $title;
    public $uploadedFiles;
    public $skill = '';

    protected function rules ()
    {
        return [
            'title' => 'required|min:3',
            'uploadedFiles' => 'required|file|mimes:png,jpg,pdf|max:5120',
            'skills' => 'required',
        ];
    }
    
    public function mount()
    {
        $this->skill = Skills::all();

        $data = [];
        $this->skills = collect($this->skill)->map(function($value) use ($data) {
            $data[$value->skill_id] = '';
            return $data;
        })->toArray();
    }

    public function updated($field) 
    {
        $this->validateOnly($field);
    }

    public function Post ()
    {
        $this->validate();

        $path = $this->uploadedFiles->store('public/storage/Posted');

        Post::create([
            'title' => $this->title,
            'uploadedFiles' => $path,
            'skill_id' => $this->skills,
            'user_id' => Auth::user()->id
        ]);

        $this->reset();
        return redirect()->back()->with('success', 'posted Successful');

    }
}

I even tried to remove this return redirect()->back()->with('success', 'posted Successful'); without it as am used to submit a form but getting that error

0 likes
34 replies
Sinnbeck's avatar

$this->skills is an array

'skill_id' => $this->skills,

You set it here in mount()

$this->skills = collect($this->skill)->map(function($value) use ($data) {
            $data[$value->skill_id] = '';
            return $data;
        })->toArray(); 
1 like
Sinnbeck's avatar

I would also assume skill to be a single item and skills to be an array. But both are array/collections?

vainway 's avatar

@Sinnbeck I used this

$this->skill = Skills::all();

        $data = [];
        $this->skills = collect($this->skill)->map(function($value) use ($data) {
            $data[$value->skill_id] = '';
            return $data;
        })->toArray();

because I wanted to select skills from skills tables and other methods I tried weren't working like

public function render()
    {
        return view('livewire.post', [
            'post' => Post::all()
        ]);
    }
Sinnbeck's avatar

@vainway but your column seems to expect 1 skill (skill_id) but you pass multiple? What do you actually want?

vainway 's avatar

@Sinnbeck I want my select2 input to get all skills stored in the skills table and save as skill_id on (posts) table skill_id is a foreign key on post table and then skills I have it as a wire:model="skills"

Sinnbeck's avatar

@vainway ok so say the user select 3 skills. Does that mean 3 new rows in the database?

vainway 's avatar

@Sinnbeck here is what I want, a user adds a title which is the class name, and then adds files he/she has and proceeds on adding skills. and as told you I have a table of skills a user gets to choose from. so help me to get rid of it ErrorException Array to string conversion

Sinnbeck's avatar

@vainway then don't let them choose multiple skills. Remove the word multiple from the select and set skills to first item

$this->skills = $this->skill->first()->id;
Sinnbeck's avatar

Or maybe you set up the wrong kind of relationship? I assume it's one to many. Maybe it's supposed to be many to many?

vainway 's avatar

@Sinnbeck no I want them to choose multiple skills, a user is allowed to choose like 6 skills so, that's why I have multiple

vainway 's avatar

@Sinnbeck in my relationship a user has many skills, and a post has many skills, and skills has many post. I can't paste the code right now am using my phone

vainway 's avatar

@Sinnbeck can't open a laracast série because am not a subscriber and can u please help me setting up a role table because I never used one before

Sinnbeck's avatar

You create a table named post_skill with 2 columns 'post_id' and 'skill_id'

You then add the relationship to the Post model

    public function skills()
    {
        return $this->belongsToMany(Skill::class);
    }

You then store the Post without skills and you then attach the skills

$post =         Post::create([
            'title' => $this->title,
            'uploadedFiles' => $path,
            'user_id' => Auth::user()->id
        ]);
$post->sync($this->skills); //this should be an array of the ids 
vainway 's avatar

@Sinnbeck were you saying that I create post_skill table with 2 columns 'post_id' and 'skill_id' alone without foreign keys

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Skills;
use App\Models\Post;
use App\Models\Post_skill;
use Illuminate\Support\Facades\Auth;

class Post extends Component
{
    use WithFileUploads;

    public $title;
    public $uploadedFiles;
    public $skill = '';

    protected function rules ()
    {
        return [
            'title' => 'required|min:3',
            'uploadedFiles' => 'required|file|mimes:png,jpg,pdf|max:5120',
            'skills' => 'required',
        ];
    }
public function render()
    {
        $this->skills = Skills::all();
        return view('livewire.post', [
            'skills' => $this->skills,
        ]);
    }

public function Post ()
    {
        $this->validate();

        $path = $this->uploadedFiles->store('public/storage/Posted');

        
		$post =   Post::create([
            'title' => $this->title,
            'uploadedFiles' => $path,
            'user_id' => Auth::user()->id
        ]);
		$post->sync($this->skills);

        $this->reset();
        return redirect()->back()->with('success', 'posted Successful');

    }

migration

<?php

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

class CreatePost_skillsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_skills', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('post_id');
            $table->bigInteger('skill_id');
            $table->timestamps();
        });
    }

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

@vainway please reread my post. Both table name and one of the columns has the wrong name

vainway 's avatar

@Sinnbeck that's what I did right, try to correct me then with an example and I even added that: in post Model

public function skills()
    {
        return $this->belongsToMany(Skills::class);
    }
Sinnbeck's avatar

@vainway the name of the table is post_skill not post_skills. And your Skill model should not have an s on the end. Classes are singular

vainway 's avatar

@Sinnbeck @mcadio I did as you told me but am still getting errors

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Skill;
use App\Models\Post;
use App\Models\Post_skill;
use Illuminate\Support\Facades\Auth;

class Post extends Component
{
    use WithFileUploads;

    public $title;
    public $uploadedFiles;
    public $skill = '';

    protected function rules ()
    {
        return [
            'title' => 'required|min:3',
            'uploadedFiles' => 'required|file|mimes:png,jpg,pdf|max:5120',
            'skills' => 'required',
        ];
    }
public function render()
    {
        $this->skills = Skill::all();
        return view('livewire.post', [
            'skills' => $this->skills,
        ]);
    }

public function Post ()
    {
        $this->validate();

        $path = $this->uploadedFiles->store('public/storage/Posted');

        
		$post =   Post::create([
            'title' => $this->title,
            'uploadedFiles' => $path,
            'user_id' => Auth::user()->id
        ]);
		$post->sync($this->skills);
		// $post->skills()->attach($this->skills); even this one it's not working
        $this->reset();
        return redirect()->back()->with('success', 'posted Successful');

    }

migration

<?php

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

class CreatePostSkillTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_skill', function (Blueprint $table) {
            $table->bigInteger('post_id')->unsigned();
            $table->bigInteger('skill_id')->unsigned();
            
            $table->foreign('post')->references('id')->on('post')->onDelete('cascade');
            $table->foreign('skill_id')->references('id')->on('skills')->onDelete('cascade');
        });
    }

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

Post model

public function skill()
    {
        return $this->belongsToMany(Skill::class, 'post_skill', 'post_id', 'skill_id');
    }

result error am getting is this:

Illuminate\Database\QueryException
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '[{"id":1,"name":"PHP","user_id":1,"created_at":"2022-09-03T09:35:07.000000Z","updated_at":"2022-09-03T09:35:07.000000Z"},{"id":2' for column `students`.`post`.`skill_id` at row 1 (SQL: insert into `post` (`title`,  `uploadedFiles`, `skill_id`, `created_at`, `updated_at`);

post.blade.php

<div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label class="bmd-label-floating">Skills required for your project?</label>
                    <div wire:ignore class="bootstrap-tagsinput info-badge">
                        <select wire:model="skills" class="form-control js-select2-multi" data-placeholder="Enter Skills here..." multiple>                            
                            @foreach($skills as $skill)
                                    <option value="{{ $skill->id }}">{{ $skill->name }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
        </div>

please show me what I can change to make it work, or that post_skill table is not connected with post

Sathish NP's avatar

@vainway Post::create([ 'title' => $this->title, 'uploadedFiles' => $path, 'skill_id' => $this->skills, 'user_id' => Auth::user()->id ]);

When you are storing use implode to convert $this->skills to string and then assign to skill_id

vainway 's avatar

@sathish-SEET I used you method but it's not working

$post = Post::create([ 'title' => $this->title, 'uploadedFiles' => $path, 'skill_id' => $this->skills, 'user_id' => Auth::user()->id ]);
$post = implode(" ",$post);
return $post;
vainway 's avatar

@sinnbeck @sathish I kinda figured out how to get rid of it

$this->skills = Skills::all();
        return view('livewire.post', [
            'skills' => $this->skills,
        ]);

but I got a new error

Illuminate\Database\QueryException
SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '[{"id":1,"name":"PHP","user_id":1,"created_at":"2022-09-03T09:35:07.000000Z","updated_at":"2022-09-03T09:35:07.000000Z"},{"id":2' for column `students`.`post`.`skill_id` at row 1 (SQL: insert into `post` (`title`,  `uploadedFiles`, `skill_id`, `created_at`, `updated_at`);

it's like pulling all the data and all columns from skills tables even though am picking like 3 or 5 skills to be added in the post table. me I just want to keep skills that are being selected by a user only not all of them

mcadio's avatar

Would you consider changing the relationship and adding a pivot type relationship table? post_id, user_id, skill_id

OR, if the user is only selecting a few skills to display and it isn't just for that particular post, a simpler user_skills table to handle those lookups?

Might be easier in the long run - not sure if I'm right but so far coloring inside the lines tends to work best.

Snapey's avatar

You cannot store multiple skill_id in a single field. Stop trying to find a way around it and realise that you need a many to many relationship and change your design to suit

vainway 's avatar

@Snapey can you show within my codes and I don't a problem on changing anything

mcadio's avatar

You want to create the many to many relationship as @sinnbeck stated

$post = Post::create([
            'title' => $this->title,
            'uploadedFiles' => $path,
            'user_id' => Auth::user()->id
        ]);
$post->skills()->attach($this->skills);

That last line will create the records in the post_skills table (pivot table) in a simple way. You can also remove them just as easily. Here is the documentation on that https://laravel.com/docs/9.x/eloquent-relationships#many-to-many

You will need another table in your db to make it work, but it is worth the effort.

1 like

Please or to participate in this conversation.