HaydenHunter
7 months ago
1324
2
Laravel

fputcsv() expects parameter 2 to be array, object given

Posted 7 months ago by HaydenHunter

Trying to export my database data as a csv file, but it needs the second parameter as an array- as the error obviously states. Here's my function:

public function get_export()
    {
	    $table = DB::table('student')
	    ->join('school', 'student.schools_id', '=', 'school.school_id')
	    ->select('student.student_id', 'student.first_name', 'student.last_name', 'school.school_name')
	    ->get()
	    ->toArray();

	    $file = fopen('student.csv', 'w');

	    foreach ($table as $key) {
		    fputcsv($file, $key);
	    }

	    fclose($file);
        return Redirect::to('home');
    }

This gives me the error "fputcsv() expects parameter 2 to be array, object given"

And I've tried setting $key to an array after the foreach like:

fputcsv($file, $key->toArray());

But still getting an error. And honestly it may be some other part messing up because this is my first attempt at exporting .csv files. Any help would be greatly appreciated.

Please sign in or create an account to participate in this conversation.