3unoia.id
3unoia.id

Reputation: 25

Using View::share in Laravel 5.3

I'm trying to use View::share to pass data to all my views. All I do is like this on my AppServiceProvider

public function boot()
    {
        $stok = Produk::where('jumlah_stok', 0);
        View::share('stok', $stok);
    }

and when I'm trying to checking it on my view. it shows error like this htmlspecialchars() expects parameter 1 to be string, object given (View: E:\xampp\htdocs\sippo\resources\views\master.blade.php)

<ul class="nav">
                    @if(Auth::user()->admin==0)
                        <li><a href="/"><i class="lnr lnr-home"></i><span>Dashboard{{$stok}}</span></a></li>

Am I wrong or there is something else I should do?

Upvotes: 1

Views: 75

Answers (1)

sushibrain
sushibrain

Reputation: 2790

There are a few problems with this.

Number one:

by doing this: Produk::where('jumlah_stok', 0) you're getting a query builder object. I assume you want one single record, so you should do: Produk::where('jumlah_stok', 0)->first()


Number two:

When you try to use your variable in your view, you use double brackets ({{$stok}}). Laravel will sanitize this input, and try to force it through htmlspecialchars(), which won't work, because htmlspecialchars() expects a string, and right now, you're feeding it a query builder object. If you wish to use unsanitized variables in your views, use this syntax: {!! $stok !!}.


Number three:

Even if you were to update both of the previous things, you'd most likely still not end up with the wanted result, since you'll echo a collection to a view. Now, I don't know the structure of your database table, but let's say the Product table has a row called name, you'd have to do the following in your view: {{ $stok->name }} (*{!! $stok->name !!} would also work, but it'd be unsanitized).

Hope this helped. Cheers!

Upvotes: 1

Related Questions