在Laravel 5.6 API中按名称选择

时间:2019-02-12 13:30:32

标签: php laravel laravel-5 laravel-5.6

我的数据库中有很多广告,我想尝试按名称从主题中选择一个,但返回的是空值

 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']);
    }

这就是我在邮递员中得到的:

  

{       “成功”:是的,       “ ads”:null,       “ message”:“广告读取成功”}

1 个答案:

答案 0 :(得分:1)

在深入研究之前,需要注意一些事项:

  1. 您需要具有Request变量,以便您可以获取用户输入,或者如果它是静态的,则只需将其提供为静态。但是,static没有意义,因此我提供了将使用输入变量的代码。

  2. 您需要将值与列名进行比较才能获取它。

  3. 模型名称应为单数形式,并以与类名称相同的大写字母开头,因此您应使用Ad而不是ads,ads适用于表名,而不适合模型名。

    < / li>

考虑到上述注意事项,以下代码将为您服务:

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']);
        }
相关问题