Laravel: getting a single value from a MySQL query

To get a single value from a MySQL query in Laravel, you can use the value method on a query builder instance. For example, if you want to get the value of a single column from a row in a table, you can use the following code:

<?php

$value = DB::table('table_name')
  ->where('column_name', '=', 'value')
  ->value('column_to_retrieve');

This will execute a SELECT query that returns a single value. If you want to retrieve multiple columns, you can use the first method instead, which will return a stdClass object with properties for each column.

<?php

$row = DB::table('table_name')
  ->where('column_name', '=', 'value')
  ->first(['column_1', 'column_2']);

echo $row->column_1;
echo $row->column_2;

Watch a course Learn object oriented PHP

Keep in mind that these methods will throw an exception if no results are found. You can use the exists method to check if a row exists before trying to retrieve it.

<?php

if (
  DB::table('table_name')
    ->where('column_name', '=', 'value')
    ->exists()
) {
  // row exists, do something
}