How to Use Count() in Controller?

How do I get the number of rows here? When I use $count = $flights->count(); I get this error Count all elements in an array, or something in an object

public function index(Request $request)
        {
            $airline  = airline::all(); 
            $search = $request->get('search');
                    if($search!=""){
                        $flights =  DB::table('flights')
                        ->join('airlines', 'flights.AirlineId', '=', 'airlines.id')
                        ->select('flights.*', 'airlines.name', 'airlines.country','airlines.logo')
                        ->where(DB::raw("CONCAT(flights.id,' ',flights.flightDesignator,' ',airlines.country,' ',airlines.name,' ',flights.departureFrom,' ',flights.arriveTo,' ',flights.departureTime,' ',flights.ArrivalTime)"),'LIKE','%'.$search.'%')
                        ->paginate(4);
                $flights->appends(['search' => $search]);
                $count = $flights->count();
                if($count == 0)
                return view('admin.flights')->with(['flights' => $flights,'airline' => $airline, 'NoFound' => 'There is no result 😔']);
                else
                return view('admin.flights')->with(['flights' => $flights,'airline' => $airline,'found' => ' records founded']);
               
                
            }
    }
3

2 Answers

There is pagination is used so just change

$count = $flights->count(); to $count = $flights->total();

try to use collection

$data = collect($flights);

and then you can count it with

$data->count(); 
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest