【问题标题】:Laravel 8 PUT routes return 404Laravel 8 PUT 路由返回 404
【发布时间】:2021-07-13 17:27:08
【问题描述】:

我正在尝试通过 API 更新数据库中的数据,但它返回错误 404 not found in postman。

api.php

    // PUT update citizen from NIC
Route::put('updateCitizen/{nic}',[CitizensController::class, 'updateCitizen'] );

controller.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Citizen as ModelsCitizen;
use DB;
use Illuminate\Support\Facades\DB as FacadesDB;

class CitizensController extends Controller
{
    public function updateCitizen(Request $request, $nic)
    {

        $citizen = FacadesDB::table('citizens')
            ->where('nic', '=', $nic)
            ->update(['options->enabled', true]);

        return response()->json($citizen);
    }
}

【问题讨论】:

    标签: sql laravel eloquent laravel-8


    【解决方案1】:

    为什么不使用 api 资源方法 insted,写入 imo 看起来要快得多。

    https://laravel.com/docs/8.x/eloquent-resources
    

    否则使用更多的'LIKE'作为where子句的字符串运算符

    【讨论】:

      【解决方案2】:

      你能改变API路由如下吗?

      Route::put('update-citizen/{nic}',[CitizensController::class, 'updateCitizen']);
      

      并运行以下命令。

      php artisan route:cache
      

      并尝试使用以下网址 - {baseUrl}/api/update-citizen/{an-existing-nic}

      【讨论】:

      • 我试过了。现在它给了我一种不同的错误(500 内部服务器错误) Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update citizens set @ 987654325@ = 选项-> 启用,1 = 1 其中nic = 970173099V) 在文件中
      • 你的这行有问题 - ->update(['options->enabled', true]);它可以是 ->update(['field_name', true]);。确保您的数据库表中有该字段。
      • 是的@lyathurai 你是对的!这就是问题所在。谢谢!
      【解决方案3】:

      问题出在更新查询中。 在查询where中,

      ->update(['options->enabled', true]);
      

      必须改成,

          ->update($request->all());
      

      将 uri 中的所有 vlaues 更新为数据库列。

      【讨论】:

        【解决方案4】:

        您的控制器顶部放置:

        use Illuminate\Support\Facades\DB;
        

        然后使用:

        $citizen = DB::table('citizens')
                 ->where('nic',$nic)
                 ->update(['options->enabled', true]);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-31
          • 2014-07-12
          • 1970-01-01
          • 2018-02-11
          • 2021-12-16
          • 2015-07-01
          • 2021-09-04
          • 1970-01-01
          相关资源
          最近更新 更多