PeraMika PeraMika - 5 months ago 16
MySQL Question

Updated one column but 'published_at' column was also updated? [Laravel 5]

In the database I have a table 'articles' with columns: '

title
', '
body
', '
published_at
', '
image_name
' (and there are also Laravel's '
created_at
' and '
updated_at
' columns).

Here is my migration for creating articles table:

public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('body');
$table->timestamp('published_at');
$table->string('image_name')->nullable;
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}


and my Article.php looks like this:

class Article extends Model
{
protected $fillable = ['title', 'body', 'published_at', 'image_name'];
protected $dates = ['published_at'];

public function setPublishedAtAttribute($value)
{
$this->attributes['published_at'] = Carbon::parse($value);
}

public function getPublishedAtAttribute($value)
{
return new Carbon($value);
}
...


I wanted to update column '
image_name
' for every record in the database (in the articles table) except the one with id=18. So, in Tinker I did the following:

DB::table('articles')->whereNotIn('id', [18])->update(['image_name' => 'pic1.jpg']);


and now '
image_name
' is 'pic1.jpg' everywhere except the row where id=18.

But, the problem is that this also updated '
published_at
' column, so now date & time for every record in the database are the same (except where id=18).

Why did this happen? I have Accessors & Mutators defined but if I understand well - they should not do anything because this command was explicit and it is related exclusively to updating '
image_name
' column?

Answer

Hey its not laravels problem.

May be your in your database you have timestamp so it will automatically change date.

Just change

$table->timestamp('published_at');

to

$table->dateTime('published_at');

and then refresh your migration.

Comments