"Нет результатов запроса для модели"
Ниже вы можете найти маршруты в коде api.php:
Код: Выделить всё
Route::prefix('area')->middleware('client')->group(function () {
Route::delete('country', [CountryController::class, 'destroyMultiple']);
Route::delete('city', [CityController::class, 'destroyMultiple']);
Route::delete('district', [DistrictController::class, 'destroyMultiple']);
Route::delete('neighborhood', [NeighborhoodController::class, 'destroyMultiple']);
Route::apiResource('country', CountryController::class);
Route::apiResource('city', CityController::class);
Route::apiResource('district', DistrictController::class);
Route::apiResource('neighborhood', NeighborhoodController::class);
});
Код: Выделить всё
public function update(UpdateCountryRequest $request, Country $country)
{
DB::transaction(function () use ($request, $country) {
$country->update($request->only(['country_abbreviation', 'country_code', 'logo', 'status']));
$delete = [];
foreach ($request->languages as $language) {
$countryName = $country->CountryNames()->updateOrCreate([
'lang_id' => $language['lang_id'],
'country_id' => $country->id,
], $language);
$delete[] = $countryName->id;
}
CountryLanguage::where('country_id', $country->id)->whereNotIn('id', $delete)->delete();
});
return response()->json([
'message' => 'Country updated successfully',
'status' => 'success',
]);
}
Код: Выделить всё
public function authorize(): bool
{
if ($this->user()->isAdmin) {
return true;
}
return false;
}
public function rules(): array
{
$country = $this->route('country');
return [
'country_abbreviation' => ['required', 'string', Rule::unique('countries')->ignore($country->id)], // keeping the same country_abbreviation seperately
'country_code' => ['required', 'string', 'max:5', Rule::unique('countries')->ignore($country->id)],
'logo' => ['required', 'string', 'max:255'],
'status' => ['required', 'boolean'],
'languages' => ['required', 'array'],
'languages.*.lang_id' => ['required', 'integer', 'exists:languages,id'],
'languages.*.country_name' => ['required', 'string'],
];
}

Но для других контроллеров, когда я отправляю запрос PUT, я получаю упомянутую ошибку:
«Нет результатов запроса для модели»
Например, позвольте мне дать вам те же коды для DistrictController:
Обновить метот внутри файла контроллера:
Код: Выделить всё
public function update(UpdateDistrictRequest $request, District $district)
{
DB::transaction(function () use ($request, $district) {
$district->update($request->validated());
});
return response()->json(['message' => 'District updated successfully'], 200);
}
Код: Выделить всё
UpdateDistrictRequestКод: Выделить всё
public function authorize(): bool
{
if ($this->user()->isAdmin) {
return true;
}
return false;
}
public function rules(): array
{
return [
'service_id' => 'required|integer',
'city_id' => 'required|integer|exists:cities,id',
'name' => 'required|string|max:255',
'status' => 'required|boolean',
];
}
[img]https://i.sstatic. net/ohDixxA4.png[/img]
Я проверил, существует ли район с данным идентификатором и существует ли он в базе данных.

Ниже вы можете найти миграции:
Страна:
Код: Выделить всё
Schema::create('countries', function (Blueprint $table) {
$table->id();
$table->string('country_abbreviation');
$table->string('country_code');
$table->string('logo');
$table->tinyInteger('status');
$table->timestamps();
});
Код: Выделить всё
Schema::create('districts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('service_id')->nullable();
$table->unsignedBigInteger('city_id');
$table->foreign('city_id')->on('cities')->references('id')->onDelete('cascade');
$table->string('name');
$table->boolean('status')->default(1);
$table->timestamps();
});
Страна:
Код: Выделить всё
use HasFactory;
protected $guarded = [];
protected $fillable = [
'country_abbreviation',
'country_code',
'logo',
'status'
];
// ... Relationship methods
Код: Выделить всё
protected $guarded = [];
protected $fillable = [
'service_id',
'city_id',
'name',
'status'
];
// ... Relationship methods
Я пробовал изменить определения маршрутов внутри api.php. Например, перемещение строки DistrictCotroller в начало, но она по-прежнему выдает ту же ошибку, в то же время, когда я делаю этот запрос CountryController, все еще работает правильно.
исключение выдается этим методом внутри src > Illuminate > Routing > ImlicitRouteBinding.php
Код: Выделить всё
public static function resolveForRoute($container, $route)
{
$parameters = $route->parameters();
$route = static::resolveBackedEnumsForRoute($route, $parameters);
foreach ($route->signatureParameters(['subClass' => UrlRoutable::class]) as $parameter) {
if (!$parameterName = static::getParameterName($parameter->getName(), $parameters)) {
continue;
}
$parameterValue = $parameters[$parameterName];
if ($parameterValue instanceof UrlRoutable) {
continue;
}
$instance = $container->make(Reflector::getParameterClassName($parameter));
$parent = $route->parentOfParameter($parameterName);
$routeBindingMethod = $route->allowsTrashedBindings() && in_array(SoftDeletes::class, class_uses_recursive($instance))
? 'resolveSoftDeletableRouteBinding'
: 'resolveRouteBinding';
if (
$parent instanceof UrlRoutable &&
!$route->preventsScopedBindings() &&
($route->enforcesScopedBindings() || array_key_exists($parameterName, $route->bindingFields()))
) {
$childRouteBindingMethod = $route->allowsTrashedBindings() && in_array(SoftDeletes::class, class_uses_recursive($instance))
? 'resolveSoftDeletableChildRouteBinding'
: 'resolveChildRouteBinding';
if (
!$model = $parent->{$childRouteBindingMethod}(
$parameterName,
$parameterValue,
$route->bindingFieldFor($parameterName)
)
) {
throw (new ModelNotFoundException)->setModel(get_class($instance), [$parameterValue]);
}
} elseif (!$model = $instance->{$routeBindingMethod}($parameterValue, $route->bindingFieldFor($parameterName))) {
// EXCEPTION
throw (new ModelNotFoundException)->setModel(get_class($instance), [$parameterValue]);
}
$route->setParameter($parameterName, $model);
}
}
Код: Выделить всё
// CountryController update
public function update(UpdateCountryRequest $request, int $id)
{
dd($id, District::find($id)); // 1, District {#1444 ...}
// DistrictController update
public function update(UpdateDistrictRequest $request, int $id)
{
dd($id, District::find($id)); // 1, null
[img]https: //i.sstatic.net/pzH8uePf.png[/img]
Подробнее здесь: https://stackoverflow.com/questions/784 ... -for-model
Мобильная версия