Laravel Check If Related Model Exists

In Laravel, you can use the exists method on a relationship to check if it has any related models. For example:

<?php

$user = App\User::find(1);

if ($user->posts->exists()) {
  // $user has at least one post
}

This will check if the $user model has any related Post models.

If you only want to check if a specific related model exists, you can use the where method to filter the relationship before calling the exists method:

<?php

if (
  $user
    ->posts()
    ->where('title', '=', 'My First Post')
    ->exists()
) {
  // $user has a post with the title "My First Post"
}

Keep in mind that the exists method will execute a database query, so you should use it sparingly to avoid unnecessary performance overhead.