Laravel: getting a a single value from a MySQL query

前端 未结 6 1786
[愿得一人]
[愿得一人] 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 17:56

    [EDIT] The expected output of the pluck function has changed from Laravel 5.1 to 5.2. Hence why it is marked as deprecated in 5.1

    In Laravel 5.1, pluck gets a single column's value from the first result of a query.

    In Laravel 5.2, pluck gets an array with the values of a given column. So it's no longer deprecated, but it no longer do what it used to.

    So short answer is use the value function if you want one column from the first row and you are using Laravel 5.1 or above.

    Thanks to Tomas Buteler for pointing this out in the comments.

    [ORIGINAL] For anyone coming across this question who is using Laravel 5.1, pluck() has been deprecated and will be removed completely in Laravel 5.2.

    Consider future proofing your code by using value() instead.

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

提交回复
热议问题