DEV Community

Mahmoud Ramadan
Mahmoud Ramadan

Posted on

Two Overlooked Laravel Features: `fresh()` and Attribute Visibility

πŸ” 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');
Enter fullscreen mode Exit fullscreen mode

πŸ‘€ 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.

What's less commonly known is that 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
    ];
}
Enter fullscreen mode Exit fullscreen mode

πŸš€ Dive into more tips and help others learn:
https://github.com/digging-code-blog/community-tips

Top comments (0)