Skip to content
Advertisement

Read first record of array instead of first character in Laravel

I’m using Laravel 8 . I’ve saved some array in my database and when I try to read those arrays I just get a single character of it.

For example the array in database is ["one", "two"] and when i write

@foreach ($xs as $x)
    <li>
           {{ $x->y[0] }}
    </li>
@endforeach

it will just show ‘[‘ instead of ‘one’

in my migration file i did this :

$table->json('y');

and in my model i did this :
    protected $casts = [
        'y' => 'json',
    ];

and also in model i did try this :

 protected $casts = [
        'y' => 'array',
    ];

and in my controller i did something like this one to show data :

 public function showData(){
        $x = DB::select('select * from x');

        return view('home',['x'=>$x]);
    }

Advertisement

Answer

I’ve solved the problem. the problem was the way that i’ve called the record on table. I missed adding

use AppMyModel;

to my controller. and in my controller i used to write

$x = DB::(select * from mytable);

which I changed it to :

$x= MyModel::all();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement