使用查询生成器从数据库中以字符串形式获取值

问题描述

所以在控制器中,我从字符串(即product_name)的输入表单中获取

return $request->input('product_name');

为此,我想使用查询生成器从数据库表中获取该产品的product_id

return category::where('product_name',$request->input('product_name'))->get('product_id');

问题是,我正在获取数组形式的值,但我希望此值在字符串中

//输出

[{“ product_id”:7}]

但是我想要像这样的字符串

7

请先使用查询生成器帮助实现此目的,

解决方法

这应该有效:

 return category::where('product_name',$request->input('product_name'))
->first()->pluck('product_id');

您似乎只想要一个条目。为此,您应该使用first()而不是get()

,

使用value方法获得一个值:

category::where('product_name',$request->input('product_name'))
    ->value('product_id')

Laravel 5.8 Docs - Queries - Retrieving Results - Retrieving A Single Row / Column From A Table value