Метод wasRecentlyCreated
Метод wasRecentlyCreated применяется к экземпляру модели Eloquent
и возвращает логическое значение true, если модель была создана
в текущем запросе (например, после вызова save или create),
и false в противном случае. Метод не принимает параметров
и полезен для определения, была ли операция сохранения созданием
или обновлением существующей записи.
Синтаксис
<?php
$model->wasRecentlyCreated();
?>
Пример
Давайте создадим новую статью и проверим, была ли она только что создана:
<?php
namespace AppHttpControllers;
use AppModelsArticle;
use IlluminateHttpRequest;
class ArticleController extends Controller
{
public function store(Request $request)
{
$article = Article::create([
'title' => 'New Article',
'content' => 'This is the content of the new article.',
'status' => 'draft',
]);
if ($article->wasRecentlyCreated()) {
return response()->json([
'message' => 'Article was created successfully.',
'article' => $article,
]);
}
return response()->json([
'message' => 'Article already exists.',
'article' => $article,
]);
}
}
?>
Результат выполнения кода при создании новой записи:
{
"message": "Article was created successfully.",
"article": {
"id": 5,
"title": "New Article",
"content": "This is the content of the new article.",
"status": "draft",
"created_at": "2026-09-07 10:00:00",
"updated_at": "2026-09-07 10:00:00"
}
}
Пример
Давайте найдём существующую статью и обновим её, после чего проверим, была ли она создана:
<?php
namespace AppHttpControllers;
use AppModelsArticle;
use IlluminateHttpRequest;
class ArticleController extends Controller
{
public function update(Request $request, $id)
{
$article = Article::find($id);
if (!$article) {
return response()->json([
'message' => 'Article not found.',
], 404);
}
$article->status = 'published';
$article->save();
if ($article->wasRecentlyCreated()) {
return response()->json([
'message' => 'This is a new article.',
'article' => $article,
]);
}
return response()->json([
'message' => 'Article was updated.',
'article' => $article,
]);
}
}
?>
Результат выполнения кода при обновлении существующей записи:
{
"message": "Article was updated.",
"article": {
"id": 2,
"title": "Existing Article",
"content": "This is the content of the existing article.",
"status": "published",
"created_at": "2026-09-06 08:00:00",
"updated_at": "2026-09-07 10:05:00"
}
}
Пример
Давайте проверим поведение метода при использовании с firstOrCreate:
<?php
namespace AppHttpControllers;
use AppModelsArticle;
use IlluminateHttpRequest;
class ArticleController extends Controller
{
public function getOrCreate(Request $request)
{
$article = Article::firstOrCreate(
['title' => 'Unique Article'],
['content' => 'This article is created if not exists.',
'status' => 'draft']
);
if ($article->wasRecentlyCreated()) {
echo "Article was just created.";
} else {
echo "Article already existed.";
}
return $article;
}
}
?>
Результат выполнения кода, если запись с таким заголовком существует:
"Article already existed."
Результат выполнения кода, если запись с таким заголовком не существует:
"Article was just created."