I advice against using the database to store arrays/json strings like that, it kinda defeats the purpose of a relational database.
Jun 12, 2025
11
Level 1
Edit the last value of an array and put back into database
Hi,
I added an array in a database column and I am trying to edit the last value and insert it back into the database with the new value but its not working. Here is my code:
This is the data that is stored in the database. I am trying to change the last array so the "27.5.24" and "34".
[
[
"24.5.24", "100"
],
[
"25.5.24", "58"
],
[
"26.5.24", "49"
],
[
"27.5.24", "34"
]
}
This is the code that changes the value:
namespace App\Http\Controllers;
use App\Models\Keyword;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Redirect;
class KeywordController extends Controller
{
public function updateKeyword(string $keyword_id): RedirectResponse
{
$keyword = Keyword::find($keyword_id);
$data = $keyword->data;
if (!empty($data)) {
$data[count($data)-1][0] = "10.10.10";
$data[count($data)-1][1] = "150";
}
$keyword->data = $data;
$keyword->save();
}
}
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Keyword extends Model
{
use HasFactory;
protected $fillable = [
'keyword',
'projects_id',
'data',
];
protected function casts(): array
{
return [
'data' => 'array',
];
}
When I run the code, the data remains unchanged. Can someone provide some advice?
Thank you.
Please or to participate in this conversation.