Reputation: 513
I'm trying to pass a variable that contains database data to all the views with viewcomposer. But when I pass the variable to the view it says undefined index. Since I'm new to laravel I don't know that whether I'm doing it right in the Model please guide me if I'm wrong.
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Advertisement extends Model
{
public static function retreive_adds()
{
return static::all()
->toArray();
}
}
Service Provider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Advertisement;
class AddServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
view()->composer("*", function ($view){
$view->with('advertisement', \App\Advertisement::retreive_adds());
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
view
<div class="sidebar-widget sidebar-adds-widget">
@if(($advertisement[3]->is_visible == 1) && ($advertisement[6]->position == 'homepage-left-bottom'))
<div class="adds-block" style="background-image:url({{ asset('uploads/advertisement_uploads') }}/{{$advertisement[1]->img_url}});">
<div class="inner-box">
<!-- <div class="text"></span></div>
<a href="#" class="theme-btn btn-style-two"></a> -->
</div>
</div>
@elseif(($advertisement[3]->is_visible == 0) && ($advertisement[6]->position != 'homepage-left-bottom'))
<div class="adds-block" style="background-image:url(images/resource/add-image-3.jpg);">
<div class="inner-box">
<div class="text">Advertisement <span> 340 x 283</span></div>
<a href="#" class="theme-btn btn-style-two">Purchase Now</a>
</div>
</div>
@endif
</div>
And when I var_dump the $advertisement variable I get the array containing the values from the database also
array(1) { [0]=> array(7) { ["id"]=> int(4) ["img_url"]=> string(34) "advertisement-image-1518768862.gif" ["link"]=> string(36) "https://laravel.com/docs/5.6/queries" ["is_visible"]=> int(1) ["created_at"]=> string(19) "2018-02-16 08:14:22" ["updated_at"]=> string(19) "2018-02-16 08:14:22" ["position"]=> string(18) "homepage-right-top" } }
And if this is not the best approach, what is the best way to display a data from the db to all views ?
Upvotes: 2
Views: 3581
Reputation: 163948
You can't do this:
$advertisement[3]
Because $advertisement
is an array and not an object. You need to iterate over the collection to be able to get data from an object:
@foreach ($advertisement as $object)
{{ $object->is_visible }}
@endforeach
Upvotes: 3