Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

larabeginner22's avatar

How to export excel from searched result view

I have this search code in TaskController

public function search(Request $request)
    {
        $OngoingCount = Task::where('status', 'Ongoing')->count();
        $DelayedCount = Task::where('status', 'Delayed')->count();
        $FinishedCount = Task::where('status', 'Finished')->count();
        $tasks = Task::where([
            ['title', '!=', NULL],
            [function ($query) use ($request) {
                if (($term = $request->term)) {
                    $query->orWhere('title', 'LIKE', '%' . $term . '%')->get();
                }
            }]
        ])
            ->orderBy('created_at', 'desc')
            ->paginate(10);
            return view('tasks.index', compact('tasks', 'OngoingCount', 'DelayedCount', 'FinishedCount'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
            
    }
public function export_excel()
	{
		return Excel::download(new TaskExport, 'project.xlsx');
	}

I need to export that search result to excel

TaskExport

class TaskExport implements FromCollection, WithHeadings, ShouldAutoSize
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return task::select('id','title','pic','start','end','description','status')->get();
    }

    public function headings(): array
    {
        return ["No", "Project Name", "PIC" ,"Start Project","Deadline Project", "Description","Status"];
    }
}

index.blade.php

<a href="export" method="GET"class="btn btn-success my-3" target="_blank">EXPORT EXCEL</a>
            <div class="">
                <form action="search" method="GET" role="search">
                    <div class="input-group">
                        <span class="input-group-btn pull-left">
                            <button class="btn btn-info" type="submit" title="Search projects">
                                <span class="fas fa-search"></span>
                            </button>
                        </span>
                        <input type="text" class="form-control"  placeholder="Search projects"
                            id="term">
                    </div>
                </form>
            </div>

route web

Route::get('export', [TaskController::class, 'export_excel']);
Route::get('search', [TaskController::class, 'search']);
0 likes
2 replies

Please or to participate in this conversation.