I am having some trouble exporting my Excel file in Laravel. When I click the export button, the page displays "404 Not Found". I tried php artisan route:clear
or php artisan route:cache
but it does not work.
Hopefully, you can help me solve the problem. Here are my codes:
App\Teacher.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Teacher extends Model {
protected $guarded = [];
protected $table = 'teachers';
}
App\Exports\TeacherExport.php:
<?php
namespace App\Exports;
use App\Teacher;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class TeacherExport implements FromCollection, WithHeadings {
public function headings():array {
return [
'id',
'name',
'email',
'created_at',
'updated_at'
];
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection() {
return Teacher::all();
}
}
App\Controllers\TeachersController.php:
public function exportTeacherIntoExcel() {
return Excel::download(new TeacherExport, 'teacher.xlsx');
}
web.php:
Route::get('/teacher/export-excel', 'TeachersController@exportTeacherIntoExcel');
resources\views\teacher\index.blade.php:
@extends('home')
@section('content')
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">
Danh sách giáo viên
</h5>
<p class="card-text">
Bạn có thể tìm tất cả thông tin giáo viên ở đây:
</p>
</div>
</div>
<a href="/teacher/create" class="btn btn-info">
Thêm giáo viên
</a>
<a href="/teacher/export-excel" class="btn btn-success">
Xuất file
</a>
<table class="table thead-light">
<thead>
<tr>
<th scope="col">
ID
</th>
<th scope="col">
Tên giáo viên
</th>
<th scope="col">
Địa chỉ Mail
</th>
<th scope="col">
Tính năng
</th>
<th scope="col">
Tính năng
</th>
</tr>
</thead>
<tbody>
@foreach($teacher as $teacher)
<tr>
<th scope="row">
{{$teacher->id}}
</th>
<td>
{{$teacher->name}}
</td>
<td>
{{$teacher->email}}
</td>
<!-- <td>Tính năng</td> -->
<td>
<a href="/teacher/{{$teacher->id}}/edit" class = "btn btn-success">
Sửa
</a>
</td>
<td>
<a href="/teacher/{{$teacher->id}}" class="btn btn-danger">
Xóa
</a>
</td>
</tr>
@endforeach
</tbody>
</table>
@endsection
Thank you, everyone. I have already solved my problem. The issue here is the order of the route. In my route, I fixed it like this and it works.
web.php:
/**
* Teacher
*/
Route::get('/teacher/export-excel', 'TeachersController@exportTeacherIntoExcel');
Route::get('/teacher', 'TeachersController@index');
Route::get('/teacher/create', 'TeachersController@create');
Route::post('/teacher', 'TeachersController@store');
Route::get('/teacher/{teacher}/edit','TeachersController@edit');
Route::patch('/teacher/{teacher}', 'TeachersController@update');
Route::get('/teacher/{teacher}', 'TeachersController@destroy');