This is an obvious one, if a user isn't logged in then it's going to be NULL.
Is a user logged in?
Using Laravel 5.2 with "web" routes, I am hung up on getting Auth::user() or Auth::id() to be recognized from within a boot or __construct method of my model. It is accessible from all other methods of the model except for these.
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
class Movie extends Model
{
public static function boot() {
parent::boot();
dd(Auth::user()); //returns null...
static::updating(function($movie) {
$movie->revisions()->attach(Auth::id(), ['revisable_type' => $movie->morphClass]);
});
}
/**
* A movie may have multiple sources associated with it.
*
* @return \Illuminate\Database\Eloquent\Relations\belongsToMany
*/
public function sources() {
dd(Auth::user()); //just for testing -- returns the full User Collection
return $this->belongsToMany('App\Source');
}
}
Thanks in advance.
@ianspangler Unfortunately, by default, you can't use anything related to sessions with route model binding. Route model binding kicks in before your sessions do because the middleware responsible for booting up the sessions has not been "activated" yet in a sense. I believe the recommended method for these cases is to not use route model binding.
However, if you have to use it, then one solution would be to scrap the web middleware and move everything in that middleware group into the global middleware stack. In other words, in your app\Http\Kernel file, do this:
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
By doing so, those middlewares will run very early in the life cycle, and you will have access to the authenticated user during route model binding. You can also get rid of the web middleware in this case.
Please or to participate in this conversation.