Home > Back-end >  How to return a single output in laravel query builder
How to return a single output in laravel query builder

Time:05-21

I have a database table with the following structure.

id setting_name setting_value
1 website_name New Website
2 contact_email [email protected]
3 contact_address London, UK

Now I am using laravel to return the values of this table,

$syetem_settings = System::all()

This returns it as a collection and there is no way I can use the individual values

$syetem_settings = System::all()->toArray()

This also returns it as an array and foreach loop isn't helping me.

What I want to do I want to use this variables in the view blade. e.g

{{system_settings->website_name}} //  to return website name;
{{system_settings->contact_email}} //  to return website email;

Please what is the right code for this? I'm using php 8 and laravel 9

CodePudding user response:

If you really must have this database design, then you would need to get each setting by name from the database as single models, like this:

$websiteName = System::where('setting_name', 'website_name')->first();
$contactEmail = System::where('setting_name', 'contact_email')->first();

Then just output it like this:

{{ $websiteName }}
{{ $contactEmail }}

But if you want to have all the settings variables in one single object, then you would need all the setting_name values as actual columns. So you get ONE single model with all the values instead of one model per value.

This might not be what you want, for other reasons. So a workaround for you, with your current database design, could be something like this:

// Get all rows
$systemSettings = System::all();

// Create empty object
$settingsObject = new stdClass;

// Loop through all the rows (models)
foreach($systemSettings as $systemSetting) {
    // Get the settings_name to use as attribute name
    $attribute = $systemSetting->setting_name;
    
    // Get the settings_value to use as value for the attribute
    $value = $systemSetting->setting_value;

    // Add attribute and value to the empty object
    $settingsObject->$attribute = $value;
}

This should give you an object called $settingsObject that has all the rows as attribute->value. And then you could output your stuff like this:

{{ $settingsObject->website_name }} 
{{ $settingsObject->contact_email }} 

CodePudding user response:

I think you're trying to use Entity-Value architecture for your table. It could be a good idea to pluck each column data separately and then combine them as a single array:

$keys = System::pluck('setting_name')->toArray();
$values = System::pluck('setting_value')->toArray();
$arr = array_combine($keys, $values);

then you can use foreach to itrate through the combined array:

foreach($arr as $k => $v) {
  ...
}
  • Related