jeudi 1 octobre 2015

Laravel 5 how to get many random rows using collections

Based on how get random row laravel-5 I adjusted my query, but still not receiving the expected result.

I have 20 articles in the database and want to get randomly only 3 of them and show them on the page.

My class is just like the following:

public function article()
{
    $article = DashArticle::where('category', '=', 0)->get()->random(3);

    $articleTitle0       = $article[0]->titel;
    $articleAutor0       = $article[0]->autor;
    $articleAbstract0    = $article[0]->abstract;
    $articleSource0      = $article[0]->source;
    $articleTitle1       = $article[1]->titel;
    $articleAutor1       = $article[1]->autor;
    $articleAbstract1    = $article[1]->abstract;
    $articleSource1      = $article[1]->source;
    $articleTitle2       = $article[2]->titel;
    $articleAutor2       = $article[2]->autor;
    $articleAbstract2    = $article[2]->abstract;
    $articleSource2      = $article[2]->source;

    return compact(
        'articleTitle0', 'articleAutor0', 'articleAbstract0', 'articleSource0',
        'articleTitle1', 'articleAutor1', 'articleAbstract1', 'articleSource1',
        'articleTitle2', 'articleAutor2', 'articleAbstract2', 'articleSource2'
    );
}

And here part of the view:

<div id="a-slide" class="carousel slide auto panel-body">
    <ol class="carousel-indicators out">
        <li class="active" data-slide-to="0" data-target="#a-slide"></li>
        <li class="" data-slide-to="1" data-target="#a-slide"></li>
        <li class="" data-slide-to="2" data-target="#a-slide"></li>
    </ol>
    <div class="carousel-inner">
        <div class="item active" style="padding: 0 16px;">
            <p style="font-size: 16px; font-weight: bold;">{!! $articleTitle0 !!}</p>
            <p class="text-muted">{!! $articleAutor0 !!}</p>
            <p><strong>Abstract:</strong><br />{!! $articleAbstract0 !!}</p>
            <p>
                <a href="$articleSource !!}" target="_blank">
                    {!! $articleSource0 !!}
                </a>
            </p>
        </div>

        <div class="item" style="padding: 0 16px;">
            <p style="font-size: 16px; font-weight: bold;">{!! $articleTitle1 !!}</p>
            <p class="text-muted">{!! $articleAutor1 !!}</p>
            <p><strong>Abstract:</strong><br />{!! $articleAbstract1 !!}</p>
            <p>
                <a href="{!! $articleSource1 !!}" target="_blank">
                    {!! $articleSource1 !!}
                </a>
            </p>
        </div>

The problem is when I let the random = 3 ($article = DashArticle::where('category', '=', 0)->get()->random(3); I get following error: "Undefined offset: 1"

and when I user random = 20 (the total number of rows in the table) it works but I don't become any random articles but always the first 3 lines of the table.

I would appreciate any help! Thanks!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire