PHP code example of ankurk91 / laravel-eloquent-relationships

1. Go to this page and download the library: Download ankurk91/laravel-eloquent-relationships 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/ */

    

ankurk91 / laravel-eloquent-relationships example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Ankurk91\Eloquent\HasBelongsToOne;
use Ankurk91\Eloquent\Relations\BelongsToOne;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Restaurant extends Model
{
    use HasBelongsToOne;
    
    /**
     * Each restaurant has only one operator.
     */
    public function operator(): BelongsToOne
    {
        return $this->belongsToOne(User::class)          
            ->wherePivot('is_operator', true);
            //->withDefault();
    }

    /**
     * Get all employees including the operator.
     */
    public function employees(): BelongsToMany
    {
        return $this->belongsToMany(User::class)
            ->withPivot('is_operator');
    }   
}    



// eager loading
$restaurant = Restaurant::with('operator')->first();
dump($restaurant->operator);
// lazy loading
$restaurant->load('operator');
// load nested relation
$restaurant->load('operator.profile');
// Perform operations
$restaurant->operator()->update([
  'name'=> 'Taylor'
]);



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphToMany;

class Image extends Model
{ 
    public function posts(): MorphToMany
    {
        return $this->morphedByMany(Post::class, 'imageable');
    }

    public function videos(): MorphToMany
    {
        return $this->morphedByMany(Video::class, 'imageable');
    }
}



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Ankurk91\Eloquent\HasMorphToOne;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Ankurk91\Eloquent\Relations\MorphToOne;

class Post extends Model
{
    use HasMorphToOne;

    /**
     * Each post may have one featured image.
     */
    public function featuredImage(): MorphToOne
    {
        return $this->morphToOne(Image::class, 'imageable')
            ->wherePivot('featured', 1);
            //->withDefault();
    }
    
    /**
     * Get all images including the featured.
     */
    public function images(): MorphToMany
    {
        return $this->morphToMany(Image::class, 'imageable')
            ->withPivot('featured');
    }

}




// eager loading
$post = Post::with('featuredImage')->first();
dump($post->featuredImage);
// lazy loading
$post->load('featuredImage');