Lucas Gomez
Lucas Gomez

Reputation: 145

Fetching and printing a single value from database using laravel

I'm currently trying to create my settings page by creating a table settings with company_name column. My idea is to fetch the single value company_name and print it in the title of the pages and where the name is going to be appearing. I just am not sure how to convert the array return from the DB::select to be able to print it correctly.

The code:

public function __construct()
{ 
    $company_name = DB::table('settings')->select('company_name')->get();

    return View::share('company_name', $company_name);
}

And print it in the blade system as {{ $company_name }}, although it can't convert an array to string.

Upvotes: 1

Views: 5337

Answers (3)

alxscms
alxscms

Reputation: 3067

Either use eloquent (that I would recommend) which would be like this :

$company_name = Setting::first()->company_name;

or using fluent :

$company_name = DB::table('settings')->company_name;

Upvotes: 1

hannesvdvreken
hannesvdvreken

Reputation: 4968

I think you should re-think your DB schema.

But if you want an answer to keep working with you current schema:

DB::table('settings')->select('company_name')->first();

This can throw an Eloquent ModelNotFound exception.

EDIT

public function __construct()
{ 
     $result = DB::table('settings')->select('company_name')->first()->toArray();

     return View::share($result);
}

Upvotes: 0

Chrisky
Chrisky

Reputation: 567

Could you use ->first() to select the first value from the returned set?

Upvotes: 0

Related Questions