PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, November 16, 2022

[FIXED] How to update all rows of a table without retrieving them in Laravel?

 November 16, 2022     eloquent, laravel, laravel-6, mysql     No comments   

Issue

I am trying to update all rows inside one of my database tables but I am receiving the following error:

Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically

I am doing this inside a migration:

public function up()
{
    Schema::table('rooms', function (Blueprint $table) {
        $table->json('beds')->nullable();
    });

    Room::update([
        'beds' => ['One King', 'Two Doubles']
    ]);

    Schema::table('rooms', function (Blueprint $table) {
        $table->json('beds')->nullable(false)->change();
    });
}

I am adding a json column 'beds' to my existing table 'rooms' and want to set a default value of ['One King', 'Two Doubles'], I am wondering if I can do it directly in the query without loading the models.

I made up the following solution, but it feels kinda "hacky":

// All id's are bigger than 0
Room::where('id', '>', 0)->update([
    'beds' => ['One King', 'Two Doubles']
]);

Does anyone know of another way to do update all rows without the where statement?


Solution

You can call the static query() method on the model:

// ::query() return an instance of \Illuminate\Database\Eloquent\Builder
Room::query()->update([
  'beds' => ['One King', 'Two Doubles']
]);


Answered By - Brian Lee
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing