Array to string conversion error laravel

I'm performing a simple insert which I've done many times without any issues and for some odd reason it's not working and I get this error message: error: {type: "ErrorException", message: "Array to

I’m performing a simple insert which I’ve done many times without any issues and for some odd reason it’s not working and I get this error message:

error: {type: "ErrorException", message: "Array to string conversion",…}
file: "C:wampwwwstudentreg2vendorlaravelframeworksrcIlluminateDatabaseGrammar.php"
  line: 33
  message: "Array to string conversion"
  type: "ErrorException"

Here’s my code:

$advisorCheck = AdvisorCheck::create([
            'status'         => Input::get('status'),
            'application_id' => Input::get('id'),
            'user_id'        => Auth::id()
        ]);

The migration for the advisor_check table which AdvisorCheck model uses seems fine, all foreign keys are unsigned and show the relations correctly in phpmyadmin, all values from the Input::get are strings, the model has the correct fields set as fillable (status, application_id, user_id).

I’ve even tried doing this in php artisan tinker like this:

AdvisorCheck::create([ 'status' => 'returned', 'application_id' => '3', 'user_id' => '4']);

and I get this response:
Array to string conversion

I’ve also tried this method and get the same error:

$advisorCheck                 = new AdvisorCheck;
$advisorCheck->status         = Input::get('status');
$advisorCheck->application_id = Input::get('id');
$advisorCheck->user_id        = Auth::id();
$advisorCheck->save();

Model code:

<?php

class AdvisorCheck extends Eloquent {

    protected $fillable = ['status', 'application_id', 'user_id'];

    protected $table = ['advisor_check'];
}

If you need to see more code please ask.

Many thanks to anyone who can help!

@Aridez

  • Laravel Version: 5.4.31

  • PHP Version: PHP 7.0.15 (cli) (built: Jan 17 2017 13:57:33) ( NTS )
    Copyright (c) 1997-2017 The PHP Group
    Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies

  • Database Driver & Version: —

Description:

When creating custom messages as objects in order to get a specific JSON object response, some of them return an ErrorException: Array to string conversion while others allow this kind of message.

Steps To Reproduce:

Using the following bits of code to test:

class CustomRequest extends FormRequest {

    public function rules()
    {
        return [
        'email' => 'required|email|unique:users,email',
    ...
        ];
    }

    public function messages()
    {
        return [
            'email.unique' => ['error' => 'message', 'code' => '409'],
            'email.email' => ['error' => 'message', 'code' => '400'],
            ...
        ];
    }

    public function response(array $errors) {
            return Response::create($errors, 400);
    }
...
}
  • When triggering the ’email.unique’ rule the expected JSON object is returned correctly
  • When triggering the ’email.email’ rule the following error shows up:

ErrorExceptionArray to string conversion

in MessageBag.php (line 246)

at HandleExceptions->handleError(8, ‘Array to string conversion’, ‘I:APIvendorlaravelframeworksrcIlluminateSupportMessageBag.php’, 246, array(‘message’ => array(‘error’ => ‘message’), ‘format’ => ‘:message’, ‘messageKey’ => ’email’))

at str_replace(array(‘:message’, ‘:key’), array(array(‘error’ => ‘message’), ’email’), ‘:message’)in MessageBag.php (line 246)

@Aridez

Seems like in the file vendorlaravelframeworksrcIlluminateSupportMessageBag.php, the following function crashed because the message is an array.

    protected function transform($messages, $format, $messageKey)
    { 
        return collect((array) $messages)
            ->map(function ($message) use ($format, $messageKey) {
                // We will simply spin through the given messages and transform each one
                // replacing the :message place holder with the real message allowing
                // the messages to be easily formatted to each developer's desires.
                return str_replace([':message', ':key'], [$message, $messageKey], $format);
            })->all();
    }

It could be solved to take into account the cases where it received an array adding if (is_array($message)) $message = json_encode($message);:

    protected function transform($messages, $format, $messageKey)
    { 
        return collect((array) $messages)
            ->map(function ($message) use ($format, $messageKey) {
                if (is_array($message)) $message = json_encode($message);
                // We will simply spin through the given messages and transform each one
                // replacing the :message place holder with the real message allowing
                // the messages to be easily formatted to each developer's desires.
                return str_replace([':message', ':key'], [$message, $messageKey], $format);
            })->all();
    }

@themsaid

I don’t think that’s the correct use case, custom validation messages are used to describe why a certain field in your request body won’t pass validation, you can’t use it as a response to your request.

@Aridez

Continuing with this discussion, I believe that attaching a code to the message can be useful in the case of APIs. An «email» validation error seems that should return a 400 error code, but a 409 error code suits more the «unique user» error. This error is then passed to the response function, so it seemed natural to create a more complex message object there, but if that’s not the correct use case:

How would be the best way to return a different error code depending on the validation triggered?

@themsaid

A single request can trigger multiple validation errors for different input fields.

@Aridez

Thank you for your answers.

I am aware that multiple errors are returned. Right now I want to add an error code to each error to identify it more easily in the front end, the messages() function looks like:

    public function messages()
    {
        return [
            'username.required' => $this->AttributeMissing(),
            'email.required' => $this->AttributeMissing(),
            'email.email' => $this->AttributeNotWellFormed(),
            'password.required'  => $this->AttributeMissing(),
            'username.unique'  => $this->AttributeNotUnique(),
            'email.unique' => $this->AttributeNotUnique(),
        ];
    }

And the errors are packed all packed in an array that outputs:

{"errors":[
	{"status":"409",
	"code":"not_unique",
	"message":"This username is already taken"},
	{"status":"409",
	"code":"not_unique",
	"message":"This email is already taken"}
	]
}

This is to provide a more standardized error structure (following http://jsonapi.org/format/#errors) since some endpoints of the API will be available to third parties, but I don’t want a solution that enters in conflict with Laravel itself.

Any suggestions would be appreciated!

@whiterook6

I am getting the same error. Our use case for printing errors is for logging what failed validation. In some cases we use some conditional logic so these rules aren’t always present. Why not allow a way to flatten the message bag somehow?

#1 19.10.2021 07:53:07

Ошибка при записи в промежуточной таблице Array to string conversion

Всем доброго времени суток. Второй день бьюсь с проблемой. При создании записи таким вот образом:
$post = Post::create($data);
$post->tags()->sync($request->tags);
Выдает ошибку ErrorException Array to string conversion
Ниже прилагаю код модели, контроллера ну и вида на всякий.

class Post extends Model
{
    use HasFactory;
    use Sluggable;

    protected $guarded = [];

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }

    public function tags(){
        return $this->belongsToMany(Tag::class);
    }

    public function category(){
        return $this->belongsTo(Category::class);
    }
}
class Tag extends Model
{
    use HasFactory;
    use Sluggable;

    protected $guarded = [];

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }

    public function posts(){
        return $this->belongsToMany(Post::class);
    }
}

Контроллер Post

public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'category_id' => 'required|integer',
            'thumbnail' => 'nullable|image',
        ]);

        $data = $request->all();

        if($request->hasFile('thumbnail')){
            $folder = date('Y-m-d');
            $data['thumbnail'] = $request->file('thumbnail')->store("images/{$folder}");
        }

        $post = Post::create($data);
        $post->tags()->sync($request->tags);

        return redirect()->route('posts.index')->with('success', 'Запись успешно добавлена');
    }

Ну и фрагмент вида

<div class="form-group">
  <label for="tags">Тэги</label>
  <select name="tags[]" class="select2" multiple="multiple" data-placeholder="Выбор тэгов" id="tags" style="width: 100%;">
    @foreach($tags as $k => $v)
      <option value="{{ $k }}">{{ $v }}</option>
    @endforeach
  </select>
</div>

#2 19.10.2021 10:53:33

Re: Ошибка при записи в промежуточной таблице Array to string conversion

Решил проблему big_smile. Вместо метода create() сделал так:

public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'category_id' => 'required|integer',
            'thumbnail' => 'nullable|image',
        ]);

        $data = $request->all();

        if($request->hasFile('thumbnail')){
            $folder = date('Y-m-d');
            $data['thumbnail'] = $request->file('thumbnail')->store("images/{$folder}");
        }
        $post = new Post();
        $post->title = $data['title'];
        $post->description = $data['description'];
        $post->content = $data['content'];
        $post->published = $data['published'];
        $post->meta_keywords = $data['meta_keywords'];
        $post->meta_description = $data['meta_description'];
        if(isset($data['thumbnail'])){
            $post->thumbnail = $data['thumbnail'];
        }
        $post->category_id = $data['category_id'];
        $post->save();
        $post->tags()->sync($request->tags);

        return redirect()->route('posts.index')->with('success', 'Запись успешно добавлена');
    }

#3 25.11.2021 00:20:28

Re: Ошибка при записи в промежуточной таблице Array to string conversion

Привет! Я знаю откуда этот код)))) и у меня такая же ошибка. Твой метод помог!!! Только пару строчек убрал)) Спасибо!

I’m getting the error below when running seeders for my appointments table, I think this might be due to using casts property, you can see my model at the end of this post.

  ErrorException  : Array to string conversion

  at C:xampphtdocsdaisyspetvendorlaravelframeworksrcIlluminateSupportStr.php:353
    349|
    350|         $result = array_shift($segments);
    351|
    352|         foreach ($segments as $segment) {
  > 353|             $result .= (array_shift($replace) ?? $search).$segment;
    354|         }
    355|
    356|         return $result;
    357|     }

  Exception trace:

  1   IlluminateFoundationBootstrapHandleExceptions::handleError("Array to string conversion", "C:xampphtdocsdaisyspetvendorlaravelframeworksrcIlluminateSupportStr.php")
      C:xampphtdocsdaisyspetvendorlaravelframeworksrcIlluminateSupportStr.php:353

  2   IlluminateSupportStr::replaceArray("?", "insert into `appointments` (`petservice_id`, `user_id`, `fullName`, `petInfo`, `petNumber`, `comments`, `days`, `interval`, `phone`) values (?, ?, ?, ?, ?, ?, ?, ?, ?)")
      C:xampphtdocsdaisyspetvendorlaravelframeworksrcIlluminateDatabaseQueryException.php:56

  Please use the argument -v to see more details.

Appointments seede file looks like this:

<?php


use IlluminateDatabaseSeeder;


class AppointmentsSeeder extends Seeder
{
   

    public function run()
    {
        
        DB::table('appointments')->insert([
            'petservice_id' => 3,
            'user_id' => 2,
            'fullName' => 'John Doe',
            'petInfo' => 'My dog is very good',
            'petNumber' => 1,
            'comments' => 'I have no special requests',
            'days' => [ 'jueves', 'viernes' ],
            'interval' => ['5-10-2019', '15-11-2019'],
            'phone' => 6566332122
        ]);
    }
}

And migration:

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateAppointmentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('appointments', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id')->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->unsignedInteger('petservice_id')->index();
            $table->foreign('petservice_id')->references('id')->on('petservices');
            $table->string('fullName');
            $table->string('phone');
            $table->longText('petInfo');
            $table->integer('petNumber');
            $table->text('interval');
            $table->text('days');
            $table->longText('comments')->nullable();
            $table->timestamps();
        });
    }

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

And just in case my model, notice how I use casts property to transform jso into array, maybe that’s why I’m getting this error:

<?php
namespace AppModels;


use IlluminateDatabaseEloquentModel;


class Appointment extends Model
{
    
    
    protected $table = 'appointments';
    protected $casts = [ 'days' => 'array', 'interval' => 'array'];

    public function petservice()
    {
        //antes tenia hasOne
        return $this->belongsTo('AppModelsPetService', 'petservice_id');
    }

    public function user()
    {
        return $this->belongsTo('AppModelsUser', 'user_id');
    }
    
    
}

Array to string conversion error on Laravel 5.6 #55

Comments

Don’t know much what’s wrong with this error, do you have any ideas to solve this error out?
Thank you so much!

The text was updated successfully, but these errors were encountered:

Can you show us what code you wrote, just showing the error doesn’t help enough.

Actually, I don’t know exactly what went wrong. It happened when I add this package https://packagist.org/packages/yajra/laravel-datatables-oracle to my project. Seems really odd. Which code should I provide? Thanks!

Hmm what happens when you remove this package? Is it then working again? If not, then for us, it would be good to know what you did when you get this error. Did you write something to the bot? What is the code that you wrote or have you tested the BotMan Studio examples?

the problem is in concept of loading bot logic from route file because botman-resolving will be triggered for each application request even if it is absolutely unnecessary
I moved botman logic from route file to Controller handle method BotManController@handle. It solve problem globally, not only for yajra/laravel-datatables-oracle

Do not forget to add your webhook path to $except array in VerifyCsrfToken Middleware

I having the same problem with the implementation of datatable with Botman

I got same issue with Botman v.2.6.1, telegram driver v1.6.2 and Laravel 5.8. Not sure why and I do not know how to reproduce it, but sometimes, $value in closure is an array. that is why line 154.

throws exception. Still investigating. I will update when I get more information. I do not use datatable by the way as other mentioned, so I do not think this is related to datatable.

Источник

Понравилась статья? Поделить с друзьями:
  • Armoury crate asus ошибка установки
  • Armoury crate asus ошибка службы
  • Armory create ошибка установки 102
  • Armory create ошибка 2005
  • Armorstatushud как изменить расположение