Laravel eloquent update record without loading from database

PhpEloquentLaravel 5

Php Problem Overview


I'm quite new to laravel and I'm trying to update a record from form's input. However I see that to update the record, first you need to fetch the record from database. Isn't is possible to something like to update a record (primary key is set):

$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Php Solutions


Solution 1 - Php

Post::where('id',3)->update(['title'=>'Updated title']);

Solution 2 - Php

You can simply use Query Builder rather than Eloquent, this code directly update your data in the database :) This is a sample:

DB::table('post')
            ->where('id', 3)
            ->update(['title' => "Updated Title"]);

You can check the documentation here for more information: http://laravel.com/docs/5.0/queries#updates

Solution 3 - Php

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

Solution 4 - Php

The common way is to load the row to update:

$post = Post::find($id);

In your case

$post = Post::find(3);
$post->title = "Updated title";
$post->save();

But in one step (just update) you can do this:

$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);

Solution 5 - Php

You can also use firstOrCreate OR firstOrNew

// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]); 

// update record
$post->title = "Updated title";
$post->save();

Hope it will help you :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDester DezzodsView Question on Stackoverflow
Solution 1 - PhpKaJasBView Answer on Stackoverflow
Solution 2 - PhpBagaskara Wisnu GunawanView Answer on Stackoverflow
Solution 3 - PhpharrrrrrryView Answer on Stackoverflow
Solution 4 - PhpmaztchView Answer on Stackoverflow
Solution 5 - PhpRaviView Answer on Stackoverflow