Parseerror syntax error unexpected expecting laravel

On my Local server everything was good was using mailtrap mail server as smtp server. but when my website is on live server and when I trying to reset password (forgot password ) getting following ...

On my Local server everything was good was using mailtrap mail server as smtp server. but when my website is on live server and when I trying to reset password (forgot password ) getting following error screenshot is attached.I am using hostgators cpanels inbuilt smtp.
any more details I will provide if needed.enter image description here

asked Feb 14, 2018 at 12:19

Rakesh K's user avatar

3

You need to install PHP version 7.1 because nullable types were introduced in 7.1:

?string $value

And from the Laravel docs:

You will need to make sure your server meets the following requirements:

PHP >= 7.1.3

Community's user avatar

answered Feb 14, 2018 at 12:21

Alexey Mezenin's user avatar

Alexey MezeninAlexey Mezenin

155k24 gold badges283 silver badges270 bronze badges

4

For php7.0 only

If your server doesn’t have php 7.1 and above and you are only restricted to use php7.0
do as below:

  1. Delete vendor folder
  2. Delete composer.lock file
  3. Add this to composer.json file under config

    "platform": {
       "php": "7.0.0"
    }
    

As well, ensure PHP version under require is set to 7.0.0 as shown below in config.platform.php:

    "config": {
        "platform": {
            "php": "7.0.0"
        }
     }
  1. Run composer install using CMD

This now will make sure that only dependencies compatible with php7.0 are installed.

answered Dec 12, 2018 at 12:45

mutiemule's user avatar

mutiemulemutiemule

2,2122 gold badges27 silver badges34 bronze badges

4

Содержание

  1. PHP Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in laravel/framework/src/Illuminate/Foundation/helpers.php on line 476 #16674
  2. Comments
  3. Description:
  4. Steps To Reproduce:
  5. Parse error: syntax error, unexpected ‘?’, expecting variable (T_VARIABLE) in Passsword Reset #23537
  6. Comments
  7. Description:
  8. Steps To Reproduce:
  9. Laravel syntax error unexpected expecting
  10. Laravel syntax error unexpected expecting

PHP Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in laravel/framework/src/Illuminate/Foundation/helpers.php on line 476 #16674

  • Laravel Version: 5.3.26
  • PHP Version: PHP 5.6.28-1+deb.sury.org

Description:

I have a fresh install of Laravel everything is working on my local where I’m using PHP 5.6.22 but on my production server where I have php 5.6.28 I have this error :

[Tue Dec 06 10:40:56.435993 2016] [:error] [pid 3951] [client 213.55.176.229:38035] PHP Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 476

Steps To Reproduce:

install the last version of laravel with php 5.6.28

The text was updated successfully, but these errors were encountered:

Content of line 476:

Seems that your PHP version doesn’t support the splat operator, which means that it isn’t PHP5.6.

Please check the version of php running on your webserver, matches that in the console.

Ah thanks you! You are right my php cli was 5.6 but the apache version was 5.5.9

Everything is fine now

Have a nice day

Thanks. Solved it for me as well. Here’s a quick snippet for any others who may find this.

Great.
that worked for me also.

Hello. I am getting this error with php 7.1. On php 5.6.30 its works fine. 🙂

I have the same problem .. laravel 5.4 with php 7.0 or 5.6.29 doesnt works.
Any solution?
Tks

Thanks guys, I was stuck on this for so long, sannysc’s snippet worked for me on laravel 5.4 on digital ocean ubuntu 14.04 LAMP

I am having the same problem with PHP 7.0.16 too (Laravel 5.3).

Guys, just check that you’re running different PHP versions from different *nix users.

Guys check that if you are in local envirmoment and using something like MAMP that the bash profile loads the MAMP php version and not default from mac. Take a look to https://gist.github.com/irazasyed/5987693
Everytime you update mamp and your hosts php version you will need to do this.

Like vimalmistry and Sennik, I’m having the same problem with PHP 7.1.2 but working with 2 docker containers. One with nginx:1.10 and other with php:7-fpm. using laravel 5.4
When I was enabled the display_errors, I received the below message:
Parse error: syntax error, unexpected ‘$kernel’ (T_VARIABLE) in /var/www/public/index.php on line 50

Same issue here.

Have the following cron job: cd /home/user/www && php ./artisan schedule:run

This executes /usr/local/php56/bin/php artisan queue-process-listener

I’m getting the following error:

Parse error: syntax error, unexpected ‘.’, expecting ‘&’ or variable (T_VARIABLE) in /home/user/www/vendor/laravel/framework/src/Illuminate/Foundatio n/helpers.php on line 477

% php -v
PHP 5.6.29 (cli) (built: Dec 9 2016 23:39:41)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

% /usr/local/php56/bin/php -v
PHP 5.6.29 (cli) (built: Dec 9 2016 23:39:41)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2016, by Zend Technologies

Same here php7.0, laravel 5.4

Even when specifying the PHP to use (7.1.1), it produced the error.

This fixed it for me, by changing the profile to point to the MAMP 7.1.1 install, and not having to run: php composer.phar, just composer.phar

Thanks @sannysc . It Works 😀

I have also this error with php 7.1 (shows from console) and Laravel 5.4.
Check php path from your local:
$ which php
/usr/local/bin/php
Give this full path in your Crontab
* * * * * /usr/local/bin/php /Users/abhilash/my-site/artisan schedule:run >> /dev/null 2>&1

It was my first day with vagrant and laravel.
I was adding a controller with php artisan make:controller PagesController function and that was generating this error.

The issue was I was doing this from host. And host had the older version of php. I ssh’ed into the server and then ran this command again, and everything worked fine.

I hope, it will help others.

If you are using Plesk ant want to use a different PHP version you can do this: export PATH=/opt/plesk/php/7.0/bin:$PATH; php artisan key:generate (7.0 or version number of course depending on what is available on the server)

hen someone can help me out with this?
Parse error: syntax error, unexpected ‘-‘, expecting ‘]’ in /storage/ssd4/198/4185198/public_html/pr.php on line 25

im totaly new in php so pleas don’t judge me. thx

i curently have PHP version: 7.0.26

Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips

After you install php7 use this so type this into your command line so that the version changes on the shell ( export PATH=/usr/local/php71/bin:$PATH )

Hey after my research i found this working for me , replace what you have under public/.htaccess with the following

i am running ubuntu 16.04, laravel 5.6, for me, it was

sudo a2dismod php5 && sudo a2dismod php5.6 && sudo a2enmod php7.1 && sudo service apache2 restart

Where did you type that? @udoy-touhid

Laravel 5.4 require php 7.1 version for me. Lower version not working. 😀

Make sure the php version matches that on your local server. Had a similar ecounter and this should fix the issue

my php version 7.2.24 and 5.3 laravel version. any solution.?

I am facing a problem when trying to run from localhost:
I have installed PHP 7.4.7
My XAMPP folder installed in D Drive.
http://127.0.0.1:8000/ is working.
But,
http://localhost/Laravel/Laravel/public/ (Shows bellow error)

Parse error: syntax error, unexpected T_CLASS, expecting T_STRING or T_VARIABLE or ‘$’ in D:xampphtdocsLaravelLaravelpublicindex.php on line 52

At Line 52:
$kernel = $app->make(IlluminateContractsHttpKernel::class);

Источник

Parse error: syntax error, unexpected ‘?’, expecting variable (T_VARIABLE) in Passsword Reset #23537

  • Laravel Version: 5.5
  • PHP Version:7.01
  • Database Driver & Version:Mysql 5.6

Description:

On my VPS I have PHP version 7.0 installed. When A used clicks for a password reset I get this error

This relates to line 24 of RedirectIfAuthenticated.php

Researching I understand this is an issue with Mail and has been solved by others by upgrading to php7.1

I don’t have that option on my server and am forced to use php7.0 which this version of laravel 5.5 is meant to support

Can you advised how to overcome this issue please

Steps To Reproduce:

  1. Default Laravel authentication being used
  2. User clicks reset passowrd, completes form and then submits
  3. Error occurs

The text was updated successfully, but these errors were encountered:

@longestdrive Are you sure that’s the right file? On line 24 of the RedirectIfAuthenticated.php is no questionmark.

I just tried to reproduce this and everything worked as expected, without any error.

What does your RedirectIfAuthenticated.php file look like?

That’s not a core file anyway. Make the changes necessary to match the file that @tomhatzer shared above.

I’d probably make sure you truly have PHP 7.0 installed.

Make a dummy file and put in it. Look for the PHP version and make sure 7.0 is really there.

Welcome to Laravel! We are glad to have you as part of the community.

Unfortunately GitHub is not an appropriate platform for general application issues. This is only for issues/bugs with the framework code itself.

Please close your issue, and instead try asking your question on one of the many great community support areas that will likely give you a better answer more quickly:

PHP Version, everytime. Laravel 5.6 needs a minimum of PHP 7.1.X make sure you are not on an older version.

The real issue is some dependencies are using a higher PHP version other than 7.0.

You have two choices, to upgrade to PHP7.1 or instruct composer to download only dependencies which are compatible with PHP7.0 by doing the following:
For PHP7.0 only

If your server doesn’t have PHP7.1 and above and you are only restricted to use PHP7.0
do as below:

  1. Delete vendor folder
  2. Delete composer.lock file
  3. Add this to composer.json file under config

As well, ensure PHP version under require is set to 7.0.0 as shown below in config.platform.php :

  1. Run composer install using CMD

This now will make sure that only dependencies compatible with php7.0 are installed.

Источник

Laravel syntax error unexpected expecting

This exact same thing happened to me 2 days ago. I’ve easily spent a good couple of hours trying to fix it. I bet if you would make an index2.php in your public folder on the VPS, with the content , you would find that the web server (probably Apache2) is using a PHP version earlier than 5.6.4. The error message is pointing to a place where PHP 5.6’s «Splat operator» is used, so it kind of gives it away. n

To solve this, you have to disable Apache2’s PHP5 module and enable PHP7, like so: n

a2dismod php5na2enmod php7.0nsudo service apache2 restartn n

Sorry I just found out why I was getting the error. I had a Blade directive that was causing the error n

I added braces around <$expression>and it worked n

Im quite new to Laravel so I don’t really understand why that worked, but I hope this helps someone. n

a2dismod php5na2enmod php7.0nsudo service apache2 restart n

This exact same thing happened to me 2 days ago. I’ve easily spent a good couple of hours trying to fix it. I bet if you would make an index2.php in your public folder on the VPS, with the content , you would find that the web server (probably Apache2) is using a PHP version earlier than 5.6.4. The error message is pointing to a place where PHP 5.6’s «Splat operator» is used, so it kind of gives it away. n

To solve this, you have to disable Apache2’s PHP5 module and enable PHP7, like so: n

a2dismod php5na2enmod php7.0nsudo service apache2 restartn n

I hope it helps. n»,»bodyInMarkdown»:»This exact same thing happened to me 2 days ago. I’ve easily spent a good couple of hours trying to fix it. I bet if you would make an `index2.php` in your public folder on the VPS, with the content ` in your applications. If you’d prefer a head start, you might reach for one of the available first-party packages that provide robust, modern scaffolding for your authentication layer, including Laravel Breeze , an initial starter, Laravel Jetstream , offering two-factor auth, API tokens and team management, orLaravel Fortify , a backend implementation. rnrn

In this series, we’ll review how to use and customize these packages in order to fit the authentication needs of your application.rn «,»path»:»/series/laravel-authentication-options»,»strippedBody»:»rnLaravel provides several excellent options for managing authentication in your applications. If you’d prefer a head start, you might reach for one of the available first-party packages that provide robust, modern scaffolding for your authentication layer, including Laravel Breeze, an initial starter, Laravel Jetstream, offering two-factor auth, API tokens and team management, orLaravel Fortify, a backend implementation.rnrn In this series, we’ll review how to use and customize these packages in order to fit the authentication needs of your application.rn»,»thumbnail»:»https://ik.imagekit.io/laracasts/series/thumbnails/laravel-authentication.png»,»large_thumbnail»:»https://laracasts.s3.amazonaws.com/series/thumbnails/social-cards/laravel-authentication-options.png»,»svgThumbnail»:»https://ik.imagekit.io/laracasts/series/thumbnails/svg/laravel-authentication.svg»,»slug»:»laravel-authentication-options»,»episodeCount»:20,»difficultyLevel»:»Intermediate»,»customUrl»:null,»version»:null,»version_notes»:null,»complete»:1,»wallpaper»:»»,»archived»:0,»runTime»:»3h 25m»,»taxonomy»:<«name»:»Frameworks»,»path»:»https://laracasts.com/browse/frameworks»>,»hasChapters»:true,»isLarabit»:0,»isCreatorSeries»:0,»progress»:<«started»:false,»completionPercentage»:0,»episodesCompleted»:0,»completed»:false,»nextEpisodePosition»:1>,»lastUpdated»:»Jan 5, 2023″>,<«id»:142,»className»:»Laracasts\Series»,»title»:»Laravel 8 From Scratch»,»body»:»

rnWe don’t learn tools for the sake of learning tools. Instead, we learn them because they help us accomplish a particular goal. With that in mind, in this series, we’ll use the common desire for a blog — with categories, tags, comments, email notifications, and more — as our goal. Laravel will be the tool that helps us get there. Each lesson, geared toward newcomers to Laravel, will provide instructions and techniques that will get you to the finish line. rn rn

Источник

Laravel syntax error unexpected expecting

Running into a little problem with my models and a package by spatie. Hopefully you can help me out.nI am using the model clean up package by spatie to keep the database nice and cleaned up, it removes all records older then 30 days from the database. But when i add the functionality to the models i get the following error: n

FatalErrorException in BuiOrePrices.php line 12:nsyntax error, unexpected ‘:’, expecting ‘;’ or ‘<‘n n

I don’t understand what is going on in there as i use the code exactly as it is stated on the package github page.nBelow you will find the model that is causing the error. n

Did you declare strict types just before class declaration? n

Composer wouldn’t let you pull the package without having PHP7, but it only checks the CLI version as Composer is a CLI tool. n

just created a new laravel project and i get the same error on registration. I didn’t even start to write code its the default laravel authentication through make:auth. n

FatalErrorExceptionnsyntax error, unexpected ‘:’, expecting ‘;’ or ‘<‘nin Inflector.php (line 265)n n

UPDATE i need to run the project on php5.6 so i have on homestead.yaml n

— map: ImapCopyTask.testn to: /home/vagrant/Code/ImapCopyTask/publicn php: «5.6»n n

Composer wouldn’t let you pull the package without having PHP7, but it only checks the CLI version as Composer is a CLI tool. n

rnWe don’t learn tools for the sake of learning tools. Instead, we learn them because they help us accomplish a particular goal. With that in mind, in this series, we’ll use the common desire for a blog — with categories, tags, comments, email notifications, and more — as our goal. Laravel will be the tool that helps us get there. Each lesson, geared toward newcomers to Laravel, will provide instructions and techniques that will get you to the finish line. rn rn

Источник

I have an interesting situation to which I can’t figure out why it is happening. I am getting the error stated in the title. This is happening on a Blade component. I have a Blade component that accepts some values and creates Label and Input Checkbox HTML elements with those values. Now, I want to specify whether the checkbox should be «checked» or not, to which I have {{ $attributes }} on the component for that. Ternary or simple if statements both yield the same results.

input-checkbox.blade.php (the component)

@props([
'for' => 'undefined_for',
'name' => 'undefined_name',
'value' => 'undefined_value',
'aria_label' => 'undefined_aria_label'
])

<label for="{{ $for }}" class="form-label">
{{ $slot }}
</label>
<input type="checkbox"
class="form-check-input me-1"
name="{{ $name }}"
id="{{ $for }}"
value="{{ $value }}"
aria-label="{{ $aria_label }}"
{{ $attributes }}>

edit.blade.php (where component is used — note, this is all the code there is in this file)

<x-input-checkbox
name="roles[]"
for="role_{{ $role->role }}"
value="{{ $role->role }}"
aria_label="Role {{ $role->role }}"
{{ $role->checked ? 'checked' : '' }}> // <<< this is the line that causes problem
Role Label Text
</x-input-checkbox>

OR

<x-input-checkbox
name="roles[]"
for="role_{{ $role->role }}"
value="{{ $role->role }}"
aria_label="Role {{ $role->role }}"
@if($role->checked)checked@endif> // <<< this too fails
Role Label Text
</x-input-checkbox>

OR

<x-input-checkbox
name="roles[]"
for="role_{{ $role->role }}"
value="{{ $role->role }}"
aria_label="Role {{ $role->role }}"
@if($role->checked){{ 'checked' }}@endif> // <<< this too fails
Role Label Text
</x-input-checkbox>

But this does work, plain HTML.

<label for="role_{{ $role->role }}" class="form-label">
Role Label Text
</label>
<input type="checkbox"
class="form-check-input me-1"
name="roles[]"
id="role_{{ $role->role }}"
value="{{ $role->role }}"
aria-label="Role {{ $role->role }}"
{{ $role->checked ? 'checked' : '' }}> // <<< this works, the box is marked checked if true

Any assistance is greatly appreciated. Thanks.

Примерно вот так нужно было показать схему БД. Чтобы понимать как у тебя связаны таблицы между собой.
Изображение

А то, что у тебя во всех таблицах есть user_id это не беда. Беда в простом понимании связей между таблицами.
Легче же соображать, когда у тебя связь между HistoryBalance и (Person / User) прописана вот так.
Модель HistoryBalance и две примерные связи

Код: Выделить всё

public function getUser() {
        return $this->hasOne(User::className(), ['user_id' => 'user_id']);
}
public function getPerson() {
        return $this->hasOne(Person::className(), ['person_id' => 'person_id']);
}

Т.е. у тебя в модели HistoryBalance сохраняется user_id или person_id для связи с пользователем/человеком.

Внутри модели User связь с HistoryBalance

Код: Выделить всё

public function getHistoryBalance() {
        return $this->hasMany(HistoryBalance::className(), ['user_id' => 'user_id']);
}

Внутри модели Person связь с HistoryBalance

Код: Выделить всё

public function getHistoryBalance() {
        return $this->hasMany(HistoryBalance::className(), ['person_id' => 'person_id']);
}

Для того, чтобы можно было выбрать всю историю баланса Person или User.

Тебе бы переделать БД по хорошему. Переделать первичные ключи в соответствии с названием таблицы, т.е. таблица User PK (primary key — первичный ключ) — user_id, таблица Person PK — person_id, таблица HistoryBalance PK — historybalance_id. Переделать связи в моделях.
А то в скором времени у тебя будут не очень приятные запросы в твоих search.

Твоя первоначальная задача решается несколькими путями, первый и самый простой чтобы проверить будет ли у тебя выводить информацию сделали через findHistoryBalanceByUser($id) в модели HistoryBalance.
1. делается find() из HistoryBalance
2. указывается joinWith(‘person’, false, ‘LEFT JOIN’) с таблицей пользователя (ты ведь открыл Person — View, а там в $model->id указан id пользователя из модели Person)
3. указывается условие where([‘person_id’ => $id]), говорит о том, что нужно выбрать все записи с конкретным пользователем.
4. указывается сортировка orderBy
5. устанавливается лимит limit(30)
6. т.к. возврат записей, то прописываем all(), если бы возвращался запрос то ничего не прописывали бы.

Более долгий, но всё равно нужно правильная база данных.
Берем HistoryBalanceSearch в search дописываем дополнительный параметр $id.
Примерно вот так в PersonController

Код: Выделить всё

public function actionView($id)
    {
        $model = $this->findModel($id)// поиск твоей модели
        $searchModel  = new  HistoryBalanceSearch;
	$dataProvider = $searchModel->search(Yii::$app->getRequest()->get(), $id);

        return $this->render('view', [
            'model' => $model,
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

Внутри модели HistoryBalanceSearch было бы

Код: Выделить всё

public function search($params, $id = 0)
    {
        $query = HistoryBalance::find();

	if(0 < $id){
	$query
	->joinWith('person', false, 'LEFT JOIN')
	->where(['person_id' => $id])
	->orderBy(['historybalance_id' => SORT_DESC])
	->limit(30);
	}
	
        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'user_id' => $this->user_id,
            'balance' => $this->balance,
            'credit' => $this->credit,
            'balance_up' => $this->balance_up,
            'credit_up' => $this->credit_up,
            'created_at' => $this->created_at,
        ]);

        $query->andFilterWhere(['ilike', 'type', $this->type])
            ->andFilterWhere(['ilike', 'comment', $this->comment]);

        return $dataProvider;
    }

А дальше как я говорил с ListView

Код: Выделить всё

<?= ListView::widget([
	'dataProvider' => $dataProvider,
	'pager' => [
		'hideOnSinglePage' => true,
		'firstPageLabel' => Yii::t('main', 'First'),
		'lastPageLabel'  => Yii::t('main', 'Last'),
	],
	'itemView' => '_history_balance',
	'layout' => '<div class="box box-solid"><div class="box-header"><div class="pull-right">{summary}</div></div></div><div class="row">{items}</div>{pager}',
])?>

Создаешь своё представление (файл view со своими примерным именем _history_balance.php) в котором у тебя будет отрисовка информации, которая будет приходить по от контроллера $dataProvider.
Вроде бы понятно объяснил. Спрашивай конкретные вопросы, что не понял.

Понравилась статья? Поделить с друзьями:
  • Parity error что такое
  • Parameter parsing error vinf getopt not option please refer to the
  • Pantum ошибка 002
  • Pantum m7300fdn ошибка картриджа 2004
  • Pantum m7100dn ошибка 1001