How to access method in eloquent model of current user

Viewed 252

Everything what I was searching tells me about Auth::user() or auth()->user() but it gives access to result of query to DB - to all fields of record.

Here are details. Laravel 8.x There is eloquent model called User. I created also another elo model Example. There is relation in database one-to-one so table examples has foreign key user_id. In User model I created
public function example() { return $this->hasOne(); }
and in Example:
public function user() { $this->belongsTo(); }

Now I have ExampleController with public function __contruct() - if current user doesnt have related example yet I want to run view to create it.

Tell me please what is a correct way to do that - to access current user model method?

1 Answers

You could use an inline middleware

use App\Models\Example;
use Illuminate\Support\Facades\Auth;

class ExampleController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

        $this->middleware(function ($request, $next) {
            if ( Example::where('user_id', Auth::id())->doesntExist() ) { 
                return redirect('user-has-no-example');
            }

            return $next($request);
        });
    }
}
Related