Laravel eloquent version change from 5.4 to 5.8
To upgrade Laravel Eloquent from version 5.4 to 5.8, you need to follow these steps:
- Update Laravel: Before upgrading Eloquent, make sure your Laravel project is up-to-date with the latest version. You can check the latest Laravel version on the official Laravel website and update your project using Composer.
composer require laravel/laravel ^7.0
- Update your
.env
file: Laravel 5.8 requires PHP 7.2.3 or higher. Make sure you have the required PHP version installed on your server and update your.env
file accordingly.
APP_VERSION=7.0
APP_DEBUG=true
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydatabase
DB_USERNAME=myusername
DB_PASSWORD=mypassword
BROADCAST_DRIVER=redis
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
- Update your
composer.json
file: Laravel 5.8 requires PHP 7.2 and comes with Eloquent 5.8 by default. However, you need to update yourcomposer.json
file to ensure that your project uses the latest version of Eloquent.
{
"require": {
"laravel/framework": "7.0.*"
},
"autoload": {
"files": [
"vendor/autoload.php"
]
}
}
- Update your
config/app.php
file: Laravel 5.8 comes with a new service provider,App\Providers\AppServiceProvider
. You need to update yourconfig/app.php
file to register this provider.
'providers' => [
// ...
App\Providers\AppServiceProvider::class,
],
- Update your Eloquent code: Eloquent 5.8 comes with some new features and changes. Here are some of the notable changes:
- The
hasMany
andbelongsToMany
methods now accept a second argument, which is an array of relationships. This allows you to define multiple relationships with the same model.
public function users()
{
return $this->hasMany([User::class, Post::class]);
}
- The
with
method now accepts an array of relationships to eager load.
$posts = Post::with(['user', 'comments'])->get();
- The
findOrCreate
method now accepts an array of columns and their corresponding values.
$user = User::findOrCreate([
'name' => 'John Doe',
'email' => '[email protected]'
], [
'password' => Hash::make('password')
]);
- The
whereHas
method now accepts a closure as its second argument, which allows you to define complex queries on related models.
$users = User::whereHas('posts', function ($query) {
$query->where('title', 'like', '%laravel%');
})->get();
That's it! You have successfully upgraded Laravel Eloquent from version 5.4 to 5.8.