nicolaslopezj / searchable

A php trait to search laravel models
MIT License
2.01k stars 291 forks source link

'syntax error, unexpected '?'' with Laravel/PHP 5 #225

Open theinfra opened 3 years ago

theinfra commented 3 years ago

I know version 5 should not be supported, but I think this is a small change that can help legacy apps so as to not break when updated

I get the following error when installing on a fresh Laravel 5 which uses PHP 5 (any subversion)

'syntax error, unexpected '?'' vendor/nicolaslopezj/searchable/src/SearchableTrait.php:380

This is because line 380 of said file is

if ($this->relevanceField ?? false) {

Which uses the Null Coalescing Operator ?? which was introduced in PHP 7. This change was introduced in 1.11

The "correct" way to fix this would be to use a regular ternary operator, or just specify in all composer.json files from version 1.11 to require PHP 7 and above, instead of the current 5.4 which is unsoported. This way a PHP 5 installation will refuse to update from 1.10 and avoid breaking.

AlbertoSinigaglia commented 2 years ago

you can fork this repo, and then extend the trait to change the interested method, something like this:

<?php

namespace App\Extended;

trait MySQLSearchableTrait
{
    use SearchableTrait;
    protected function getRelevanceField()
    {
        if ($this->relevanceField ? $this->relevanceField : false) {
            return $this->relevanceField;
        }

        // If property $this->relevanceField is not setted, return the default
        return 'relevance';
    }
 }

and then use this trait instead of the original one