Метод 1: использование метода find
$id = 1; // Replace with the desired ID
$model = App\Models\YourModel::find($id);
if ($model) {
// The model with the given ID exists
// Code logic for existing model
} else {
// The model with the given ID does not exist
// Code logic for non-existing model
}
Метод 2. Использование метода exists
$id = 1; // Replace with the desired ID
$exists = App\Models\YourModel::where('id', $id)->exists();
if ($exists) {
// The model with the given ID exists
// Code logic for existing model
} else {
// The model with the given ID does not exist
// Code logic for non-existing model
}
Метод 3. Использование метода findOrFail
$id = 1; // Replace with the desired ID
try {
$model = App\Models\YourModel::findOrFail($id);
// The model with the given ID exists
// Code logic for existing model
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) {
// The model with the given ID does not exist
// Code logic for non-existing model
}
Метод 4. Использование метода count
$id = 1; // Replace with the desired ID
$count = App\Models\YourModel::where('id', $id)->count();
if ($count > 0) {
// The model with the given ID exists
// Code logic for existing model
} else {
// The model with the given ID does not exist
// Code logic for non-existing model
}
Метод 5: использование статического метода exists
$id = 1; // Replace with the desired ID
$exists = App\Models\YourModel::exists($id);
if ($exists) {
// The model with the given ID exists
// Code logic for existing model
} else {
// The model with the given ID does not exist
// Code logic for non-existing model
}