laravel make model find in global variable for all controllers

Viewed 310

I work in huge project , I have make relationship between account table and almost all tables,

I have to set this in every controller:

account::find(session("LoggedUser"))->relationship_table();

And it's very annoying, so is there any way to make it cleaner without repetition like global variable example:

//some where global
$user = account::find(session("LoggedUser"));
//in any controller
$user->relationship_table();

Or any idea with EXAMPLE please.

2 Answers

I think you can registered the retrieved model event:

class Account extends Model
{
    public static function booted()
    {
        static::retrieved(function ($account) {
            $account->loadMissing('relationship');
        }) 
    }
}

And optionally, you might want to register a global scope to eager load the relationship:

protected static function booted()
    {
        // The retrieved event        

        static::addGlobalScope('relationships', function (Builder $builder) {
            $builder->with('relationship');
        });
    }

So when you get a collection of accounts from a database query like this:

Account::where(...)->get();

Each account will have the relationship.

I make quick fix in controller.php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use App\Models;
class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    public $user;
    public function __construct()
    {
        BaseController::middleware(function($req, $next){
            if(session()->has("LoggedUser")){
                $this->user = Models\account::find(session("LoggedUser"));
            }elseif(session()->has("user")){
                $this->user = Models\account::find(session("owner"));
            }
            return $next($req);
        });
        
    }
}

Here a relationship

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class account extends Model
{
    use HasFactory;
    public function document()
    {
        return $this->hasMany(userDocument::class,'owner_id','id');
    }
}

And when i need to call it just write in any controller

$this->$user->document()->get();

That will get all documents that user in session own it

Maybe its not the best way but its better, I still wait for other answers make it better

Related