Serializing To Arrays
To convert a model and its loaded relationships to an array, you should use the toArray
method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:
For Example(1)
1.Create laravel project and connect to database in .env file.
composer create-project laravel/laravel blog --prefer-dist
2.Create Model Employee,Transaction
.
php artisan make:model Employee -m
php artisan make:model Transaction -m
3. Open Employee
and Transaction
Models and implement code as below
Employee.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $fillable = [
'employee_name', 'salary',
];
public function transactions()
{
return $this->hasMany('App\Transaction');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
protected $fillable = [
'employee_name', 'salary',
];
public function Employee()
{
return $this->belongsTo('App\Employee');
}
}
3.Create route in web.php to implement code.
Route::get('/SerializationToArray ', 'demoController@SerializationToArray')->name('SerializationToArray');
4.Create demoController and implement code to get all data from user model
php artisan make:controller demoController
5.Open demoController.php in app\Http\Controller folder and implement code as below
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Http\Requests;
class demoController extends AppBaseController
{
public function index()
{
$Employee = Employee::with('transactions')->first();
return $Employee->toArray();
}
}
In above example accessing data from the employee model and transactions model.
To convert only a model's attributes to an array, use the attributesToArray
method:
$Employee = Employee::first();
return $Employee->attributesToArray();
You may also convert entire collections of models to arrays:
$Employee = Employee::all();
return $Employee->toArray();