I am building a custom artisan command that needs to be able to access the database's default values for certain columns. I cannot use the attributes array. So instead I need another way.
I have tried to use Schema
. I have been able to get the table DB::table($table)
and the column names Schema::getColumnListings($table)
but not the default values.
Is there some other way to get the default values?
The Laravel Schema Builder only returns column names by design. But you can use the same approach Laravel uses internally by executing a database statement:
$results = DB::select('
select column_default
from information_schema.columns
where
table_schema = ?
and table_name = ?
', [$database, $table]);
// Flatten the results to get an array of the default values
$defaults = collect($results)->pluck('column_default'))
The above example works for a MySQL database, but you can see the approaches for other databases in the Illuminate\Database\Schema\Grammars
namespace of the Laravel source code by searching for the method compileColumnListing
.