I have a database table called random_img. Inside are 10 rows for 10 images.
I will be pulling the images from public/images/random
I want to use the database so I can set the loop to Random take(1). I want to use in my hero images. (New image on every page refresh)
Where would I put my database query so I can use it Globally? Or how can I use my RandomImgsController
so it is being used globally?
I created a route file, so I can use it as an include where needed.
Route:
Route::post('/layouts/inc/random-img','RandomImgsController@randomimg')->name('random-img');
Include:
@include('layouts.inc.random-img')
Inside Include:
@foreach ($randomimg as $rand)
<span class="hero-image">
<img src="/images/random/{{$rand->file_name}}" class="img--max--hero blur-img">
</span>
@endforeach
RandomImgsController: (Where should this go so I can use globally)
public function randomimg()
{
$randomimg = DB::table('randomimg')->orderBy(DB::raw('RAND()'))->get();
return view('random-img',compact('randomimg'));
}}
This is what I want to achieve on every page of my website:
@php
$randomimg = DB::table('randomimg')->orderBy(DB::raw('RAND()'))->get()->take(1);
@endphp
@foreach ($randomimg as $rand)
<span class="hero-image">
<img src="/images/random/{{$rand->file_name}}" class="img--max--hero blur-img">
</span>
@endforeach
What would be a cleaner way to do this?
Update:
I can access the images
DB in all views now, but I have an issue.
In my App\Http\ViewComposer\ImageComposer.php
file I have this:
public function compose(View $view)
{
$view->with('foo', Image::inRandomOrder()->get()->take(1));
}
In any view I can use {{$foo}}
to get a random row from my images table, but the data comes in a string like this:
[{"id":10,"alt":"Image Alt Tag","title":"Image Title","file_name":"10.jpg"}]
When I try to only grab individual columns like this {{$foo->file_name}}
I get the error:
Property [file_name] does not exist on this collection instance.
How can I grab individual columns like this: {{$foo->alt}}
, {{$foo->title}}
and {{$foo->file_name}}
then cleanly output them in my view? Example, I need {{$foo->file_name}}
to render like this: 5.jpg
.
Update 2:
I figured it out. Have to use @foreach
since I'm using the get()
method.
@foreach($foo as $f)
{{$f->file_name}}
@endforeach
Would still like to know if there is a way to do it without the get() method. This will work though.