PHP code example of gertjanroke / laravel-db-model

1. Go to this page and download the library: Download gertjanroke/laravel-db-model 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/ */

    

gertjanroke / laravel-db-model example snippets




namespace App\Models;

use GertjanRoke\LaravelDbModel\DBModel;

class Post extends DBModel
{
    // public $table = 'posts';
    
    // public $connection = 'mysql';
}

...

class Post extends DBModel
{
    public function scopeActive()
    {
        $this->db->where('active', true);

        return $this;
    }
}



namespace App\Models;

use App\Models\Comment;
use GertjanRoke\LaravelDbModel\DBModel;

class Post extends DBModel
{
    public function scopeActive(): self
    {
        $this->db->where('active', true);

        return $this;
    }
    
    public function scopeWithLatestComment(): self
    {
        $postTable = $this->getTable();
        $commentTable = (new Comment())->getTable();
        
        $this->db->join($commentTable, "{$commentTable}.post_id", '=', "{$postTable}.id")
            ->addSelect("{$commentTable}.body");

        return $this;
    }
}

// Inside your controller
$post = Post::active()->withLatestComment()->latest()->first();

// Keep in mind the order of calling methods doesn't matter as long as the method before returned the builder instance.
// Like this example will return the same result as the query above.
$post = Post::active()->latest()->withLatestComment()->first();