Search code examples
laravellaravel-8laravel-blade

get randomly only one record Laravel


i'm totally noob in Laravel and don't know structure and syntax of language but deadline if very soon and I don't have a time to start from scratch so I need help.

I want to display records from table randomly but from only one table must to be only one record (nested query)

is there any solution for it ?

this is my code from controller:

$alldepartments = Department::translatedIn(app()->getLocale())
            ->where('status', 1)
            ->first()
            ->inRandomOrder()
            ->get();

and this is blade:

<div style="overflow-x: scroll; overflow-y: hidden; white-space: nowrap">
                    <div class="d-flex flex-row flex-nowrap">
                        @foreach($alldepartments as $mydepartment)
                            @foreach($mydepartment->employees as $employee)
                                <div class="col-12 col-sm-6 col-lg-3">
                                    <a href="{{ url('employee/'. $employee->id) }}">
                                        <div class="single_advisor_profile wow fadeInUp" data-wow-delay="0.2s" style="visibility: visible; animation-delay: 0.2s; animation-name: fadeInUp;">
                                            <div class="advisor_thumb">
                                                <img src="{{ asset('uploads/employees/'.$employee->image) }}" alt="" />
                                            </div>
                                            <div class="single_advisor_details_info">
                                                <h6>{{$employee->name}}</h6>
                                                <p class="designation">{{$mydepartment->name}}</p>
                                            </div>
                                        </div>
                                    </a>
                                </div>
                            @endforeach
                        @endforeach
                    </div>
                </div>

it is working for randomly getting records but it gives me all record from each table but I need to take only one!!


Solution

  • You need to remove the first() method and add a take(1) before the get() method. The take() method is used to get a specific amount of elements.