touch Laravel model touch relationships in depth explanations

update updated_at of a Laravel eloquent model to the current timestamp, update relationships after the model is saved, save() options

Image for post
Image for post
Icons: touch by Gregor Cresnar, clock by Zahroe — the Noun Project

Linux:

touch filename

I- Touching Laravel Model:

Use case:

$article = Article::find($id);$article->touch();

Behind the scene:

Image for post
Image for post

II-Touching Relationships after model is saved

Use case:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{


/**
* Get the post that the comment belongs to.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
$comment->text = "something new";
$comment->save();
$this->finishSave($options)
Image for post
Image for post
// We can do:$comment->save($options);// But usually we don’t pass any array! 
$this->touchOwners();
Image for post
Image for post
$comment->save(['touch'=>$value]); // The $value is boolean which can be true/false
$this->touchOwners();
Image for post
Image for post
<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Comment extends Model
{
/**
* All of the relationships to be touched.
*
* @var array
*/
protected $touches = ['post'];
/**
* Get the post that the comment belongs to.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
public function touchOwners()
{
foreach ($this->touches as $relation) {
$this->$relation()->touch();
....
....
}
}

Written by

Web geek, Self-taught full-stack web developer, Learning Python, Laravel, Vuejs, UX/UI design, Nuclear Physicist PhD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store