在laravel 5.6 api中按名称选择

问题描述 投票:0回答:1

我在我的数据库中有很多广告,我想从主题中选择一个我尝试但我得到一个空的回报

 public function index()
    {
        # code...
       // $Ads = ads::all();
     //  return $this->sendResponse($Ads->toArray(), 'Ads read succesfully');
        $column = 'name'; // This is the name of the column you wish to search

        $Ads = ads::where($column)->first();

        return response()->json(['success'=> true,'ads'=>$Ads, 'message'=> 'Ads read succesfully']);
    }

这就是我在帖子里得到的:

{“success”:true,“ads”:null,“message”:“成功阅读”}

php laravel laravel-5 laravel-5.6
1个回答
1
投票

在挖掘之前有一些事情需要注意:

  1. 您需要具有Request变量,以便您可以获取用户输入,或者如果其静态,则只需提供静态。但是,静态没有意义所以我提供了一个将输入变量的代码。
  2. 您需要将值与列名进行比较才能获取它。
  3. 模型的名称应该是单数形式,并且以大写与类名相同,因此您应该使用广告而不是广告,广告适用于表名,而不适用于型号名称。

考虑到上述说明,以下是适用于您的代码:

public function index(\Illuminate\Http\Request $request)
        {
            # code...
            $column = 'name'; // This is the name of the column you wish to search
            $columnValue = $request->input('name');// This is the value of the column you wish to search
            $Ads = Ad::where($column, $columnValue)->first();

            return response()->json(['success'=> true,'ads'=>$Ads, 'message'=> 'Ads read succesfully']);
        }
© www.soinside.com 2019 - 2024. All rights reserved.