T
T
Tesla2015-03-23 13:14:45
Laravel
Tesla, 2015-03-23 13:14:45

How to inject loaded model into middleware?

Route:

Route::model('article', '\App\Article');
Route::get('articles/{article}', ['uses' => '[email protected]',  'middleware' => 'article.check']);

middleware:
class ArticleCheck {
  public function __construct(\App\Article $article)
  {
    dd($article->exists); // false
  }
}

The \App\Article injection in __construct() creates a new \App\Article instance, and you need to get the already loaded model.
Solution:
You can get to the model by calling the current route:
class ArticleCheck
{
  public function __construct()
  {
    $this->article = \Route::current()->getParameter('article', new \App\Article);
  }
}

This works when the middleware is bound to a route. If the middleware is global, then it is launched before routing, and the model, of course, has not yet been loaded ..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Alekseev, 2015-04-02
@orangeShadow

I want to note that it can be downloaded post

<?php namespace App\Http\Middleware;

class AfterMiddleware implements Middleware {

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question