Two Overlooked Laravel Features: `fresh()` and Attribute Visibility
Source: Dev.to
Reloading Models with fresh()
Laravel’s fresh method allows you to reload a model or an entire collection from the database, ensuring you are working with the most up-to-date data.
You can also pass relationship names to fresh, and they will be reloaded alongside the model.
use App\Models\User;
$users = User::has('comments', 1)->with('comments')->get();
// Modify the first comment locally (not persisted)
$users->first()->comments->first()->body = 'Updated body';
// Reload users and their comments from the database
$users = $users->fresh('comments');
Controlling Serialization with visible and hidden
Laravel provides the visible and hidden properties to control which attributes appear when a model is converted to an array or JSON.
These properties also accept relationship names, allowing you to explicitly show or hide relationships during serialization.
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that should be visible in arrays.
*
* @var array
*/
protected $visible = [
'name',
'email',
'created_at',
'comments', // one-to-many relationship
];
}