Laravel Code Tips #3

Bayram EKER
2 min readSep 23, 2022

--

A brief information

A quick explanation of how Laravel forwards static calls from eloquent models to the eloquent builder.

User::where('is_active', '=', true);namespace Illuminate\Database\Eloquent;class Builder implements BuilderContract
{
public function where($column, $operator = null, $value= null, $boolean = 'and')
{
// Some laravel code
}
}

For more information

1-) whereColumn()

Want to find posts that have been updated after they were created? ✍️

Or posts where the slug and title is identical?

Laravel’s whereColumn() is pretty handy! It’s makes it super easy to create this kind of queries.

Post::query()
->whereColumn('updated_at', '>', 'created_at')
->get();
Post::query()
->whereColumn('title', 'slug')
->get();

2-) Adding simple methods on your models

Laravel tip: Adding simple methods on your models can make your code at lot more readable.

class Message extends Model
{

public function markAsRead()
{
$this->read_at = now();
$this->save();
}
}
public function show(Message $message)
{

$message->read_at = now();
$message->save();
$message->markAsRead();return $message;
}

3-) If the model relationship returns null

#Laravel Tip: If the model relationship returns null, you may set a default values to the related model as a fallback Here is an example:

public function user()
{
return $this->belongsTo(User::class)
->withDefault([
'name' => 'Guest Author :)',
]);
}

Thank you for reading this article.

If you find this article useful please kindly share it with your network and feel free to use the comment section for questions, answers, and contributions.

You might also like :

--

--