Laravel: getting a a single value from a MySQL query

前端 未结 6 1785
[愿得一人]
[愿得一人] 2021-02-03 17:27

I\'m trying get a single value from MySQL database using laravel but the problem I\'m getting an array . this is my query result in MySQL command line:

select gr         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-03 18:02

    Edit:

    Sorry i forgot about pluck() as many have commented : Easiest way is :

    return DB::table('users')->where('username', $username)->pluck('groupName');
    

    Which will directly return the only the first result for the requested row as a string.

    Using the fluent query builder you will obtain an array anyway. I mean The Query Builder has no idea how many rows will come back from that query. Here is what you can do to do it a bit cleaner

    $result = DB::table('users')->select('groupName')->where('username', $username)->first();
    

    The first() tells the queryBuilder to return only one row so no array, so you can do :

    return $result->groupName;
    

    Hope it helps

提交回复
热议问题