Abdallah Sakre
Abdallah Sakre

Reputation: 915

Showing a value from the DB in a blade in laravel

Within an <option> tag, I'm trying to add the selected country from the DB.

<option>
{{ Auth::user()->cpreference()->where('qatype',1)->select('country')->first()}}
</option>

The output showing in the dropdown is as below :

{"country":"Algeria"}

How do I only show the country name ?

Upvotes: 1

Views: 40

Answers (2)

Kenny Horna
Kenny Horna

Reputation: 14241

Doing this:

Auth::user()->cpreference()->where('qatype',1)->select('country')->first()

you are getting the whole object, and given the fact that you are trying to output it its being casted to json.

To access the value of a specific property just add ->country at the end:

Auth::user()->cpreference()->where('qatype',1)->select('country')->first()->country

As a side note, I suggest you to avoid making queries in your frontend, you could get the values in your controller and then send them to the view. Also, to avoid this kind of long queries, you could define Accessors and Local Scopes in your models. Check the documentation for more info.

Upvotes: 2

Salim Djerbouh
Salim Djerbouh

Reputation: 11034

Access the property on the returned model object

<option>
{{ \Auth::user()->cpreference()->where('qatype', 1)->select('country')->first()->country }}
</option>

And having queries on your blade view does not respect separation of concern in MVC architecture

You should add an accessor to your User model like this

public function getCountryAttribute()
{
   return $this->cpreference()->where('qatype', 1)->select('country')->first()->country;
}

And make a more elegant call in your view

<option>{{ auth()->user()->country }}</option>

Hope this helps

Upvotes: 2

Related Questions