Bài viết này mình xin tổng hợp một số exception thường gặp khi phát triển các ứng dụng liên quan đến framework Laravel và các cách khắc phục chúng.
Exception
Solution
Chạy command
php artisan key:generate
Exception
Solution
Chạy command
composer install
hoặc
composer update
Note: Khi dùng composer update xin lưu ý version của các package trong composer.json ạ.
Nếu sử dụng composer install bị lỗi thì hãy kiểm tra file composer.json yêu cầu phiên bản PHP mấy thì setup host theo là được.
Exception
Solution
DB_HOST=database_host DB_DATABASE=database_name DB_USERNAME=database_username DB_PASSWORD=database_password DB_LOGQUERY=true
php artisan config:clear
Exception
Solution
Nếu class CategoryTableSeeder đúng đường dẫn, đúng tên, đúng đuôi file mà vẫn báo lỗi thì hãy chạy comand:
composer dump-autoload
Exception
Solution
{{ csrf_field() }}
hoặc
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
Note: Form::open() và Form::model() tự động generate ra token khi bạn sử dụng package illuminate/html hoặc laravelcollective/html.
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
Exception
Solution
sudo chmod -R 777 storage
sudo chmod -R 777 bootstrap/cache
Exception
Solution
Mở file AppServiceProvider.php và override lại function boot():
use Illuminate\Support\Facades\Schema; ..... public function boot() { Schema::defaultStringLength(191); }
Exception
Solution
Mass Assignment chỉ định những cột nào cho phép được sử dụng bằng cách khai báo chúng vào trong biến $fillable hoặc $guarded để đảm bảo an toàn cho DB vì chúng ta sẽ không thể biết được user sẽ đưa vào những giá trị như nào và chúng có hại hay là không.
Để sửa lỗi này, chúng ta sẽ bổ sung thêm $fillable hoặc $guarded trong Model. Ví dụ:
class Ticket extends Model { protected $fillable = ['title', 'content', 'slug', 'status', 'my_attribute']; }
Exception
Solution
Laravel sẽ không cho phép chúng ta thực hiện việc UPDATE hoặc DELETE mà không có token. Ví dụ:
<a href="{!! action('TicketsController@destroy', $ticket->slug) !!}" class="btn btn-info" onclick="return confirm('Are you sure?')" > Delete </a>
=> Cần phải sửa thành:
<form method="post" action="{!! action('TicketsController@destroy', $ticket->slug) !!}" class="pull-left"> {{ csrf_field() }} {{ method_field('DELETE') }} <div> <button type="submit" class="btn btn-warning">Delete</button> </div> </form>
Đối với việc update thì chúng ta sẽ đổi thành:
{{ method_field('PUT') }}
Exception
Solution
Lỗi này thường xảy ra khi chúng ta thực hiện findOrFail($id) hoặc firstOrFail ($id) nhưng $id bạn đang cố lấy không tồn tại trong cơ sở dữ liệu.
=> Kiểm tra lại DB và check $id nhé
Nguồn: https://viblo.asia/p/tong-hop-cac-exceptions-thuong-gap-trong-laravel
Nếu còn lỗi hoặc gặp lỗi file_put_content thì chạy 2 lệnh dưới
php artisan cache:clear php artisan config:cache