PHP code example of greabock / populator

1. Go to this page and download the library: Download greabock/populator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

greabock / populator example snippets




namespace App\Http\Controllers;

use App\Post;
use Exception;
use Greabock\Populator\Populator;
use Illuminate\Http\Request;

class PostController
{
    /**
     * @param $id
     * @param Request $request
     * @param Populator $populator
     * @return Post
     * @throws Exception
     */
    public function put(Request $request, Populator $populator): Post
    {
        $post = Post::findOrNew($request->get('id'));
        $populator->populate($post, $request->all());

        // здесь мы можем сделать что-то до того, как изменения отправятся в базу.
        
        $populator->flush();
        
        return $post;
    }
}

    $user = $populator->populate(User::class, [
        'id'    => '123e4567-e89b-12d3-a456-426655440000',
        'name'  => 'Greabock',
        'email' => '[email protected]',
        'roles' => [
            [
              'id'    => 'dcb41b0c-8bc1-490c-b714-71a935be5e2c',
              'pivot' => ['sort' => 0],
            ],
        ],
    ]);
    
    $user->relationLoaded('roles'); // true
    // хотя flush еще не сделан, все отношения уже прописаны, и нет необходимости загружать их дополнтительно.
    // Обращение к $user->roles - не вызовет повтороно запроса к бд.

    $populator->flush();
    // Только после этого сущность со всеми ее связями попадёт в базу данных.