Laravel 미들웨어는 컨트롤러에 변수를 반환합니다.
사용자가 페이지를 볼 수 있는지 여부를 확인하기 위해 권한 검사를 수행하고 있습니다. 여기에는 먼저 미들웨어를 통해 요청을 전달하는 것이 포함됩니다.
내가 가진 문제는 데이터를 뷰 자체에 반환하기 전에 미들웨어와 컨트롤러에서 동일한 데이터베이스 쿼리를 복제하고 있다는 것입니다.
다음은 설정의 예입니다.
-route.php
Route::get('pages/{id}', [
'as' => 'pages',
'middleware' => 'pageUser'
'uses' => 'PagesController@view'
]);
-PageUserMiddleware.php (클래스 PageUserMiddleware)
public function handle($request, Closure $next)
{
//get the page
$pageId = $request->route('id');
//find the page with users
$page = Page::with('users')->where('id', $pageId)->first();
//check if the logged in user exists for the page
if(!$page->users()->wherePivot('user_id', Auth::user()->id)->exists()) {
//redirect them if they don't exist
return redirect()->route('redirectRoute');
}
return $next($request);
}
-PagesController.php
public function view($id)
{
$page = Page::with('users')->where('id', $id)->first();
return view('pages.view', ['page' => $page]);
}
보시다시피 Page::with('users')->where('id', $id)->first()
미들웨어와 컨트롤러 모두에서 반복됩니다. 중복되지 않도록 데이터를 하나에서 다른 것으로 전달해야합니다.
이 작업을 수행하는 올바른 방법 (라 라벨 5.x에서)은 사용자 정의 필드를 속성 속성에 추가하는 것입니다.
소스 코드 주석에서 사용자 지정 매개 변수에 사용되는 속성을 확인할 수 있습니다.
/**
* Custom parameters.
*
* @var \Symfony\Component\HttpFoundation\ParameterBag
*
* @api
*/
public $attributes;
따라서이를 다음과 같이 구현합니다.
$request->attributes->add(['myAttribute' => 'myValue']);
그런 다음 다음을 호출하여 속성을 검색 할 수 있습니다.
\Request::get('myAttribute');
또는 laravel 5.5+의 요청 객체에서
$request->get('myAttribute');
사용자 지정 요청 매개 변수 대신 제어 반전 패턴을 따르고 종속성 주입을 사용할 수 있습니다.
미들웨어에서 Page
인스턴스를 등록합니다 .
app()->instance(Page::class, $page);
그런 다음 컨트롤러에 Page
인스턴스가 필요하다고 선언 합니다.
class PagesController
{
protected $page;
function __construct(Page $page)
{
$this->page = $page;
}
}
Laravel은 자동으로 종속성을 해결하고 Page
미들웨어에 바인딩 한 인스턴스로 컨트롤러를 인스턴스화합니다 .
laravel> = 5 $request->merge
에서는 미들웨어에서 사용할 수 있습니다 .
public function handle($request, Closure $next)
{
$request->merge(array("myVar" => "1234"));
return $next($request);
}
그리고 컨트롤러에서 :
public function index(Request $request)
{
$myVar = $request->instance()->query('myVar');
...
}
미들웨어에서 컨트롤러로 데이터를 전달할 수 있다면 Laravel 문서에있을 것입니다.
In short, you can piggy back your data on the request object which is being passed to the middleware. The Laravel authentication facade does that too.
So, in your middleware, you can have:
$request->myAttribute = "myValue";
As mentioned in one of the comments above for laravel 5.3.x
$request->attributes->add(['key => 'value'] );
Doesn't work. But setting the variable like this in the middleware works
$request->attributes->set('key', 'value');
I could fetch the data using this in my controller
$request->get('key');
Laravel 5.7
// in Middleware register instance
app()->instance('myObj', $myObj);
and
// to get in controller just use the resolve helper
$myObj = resolve('myObj');
It is very simple:
Here is middleware code:
public function handle($request, Closure $next)
{
$request->merge(array("customVar" => "abcde"));
return $next($request);
}
and here is controller code:
$request->customVar;
$request is the array so that we can just add value and key to the array and get the $request with this key in the controller.
$request['id'] = $id;
If your website has cms pages which are being fetched from database and want to show their titles in the header and footer block on all pages of laravel application then use middleware. Write below code in your middleware:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
public function handle($request, Closure $next)
{
$data = DB::table('pages')->select('pages.id','pages.title')->where('pages.status', '1')->get();
\Illuminate\Support\Facades\View::share('cms_pages', $data);
return $next($request);
}
Then goto your header.blade.php and footer.blade.php and write below code to add links of cms pages:
<a href="{{ url('/') }}">Home</a> |
@foreach ($cms_pages as $page)
<a href="{{ url('page/show/'.$page->id) }}">{{ $page->title }}</a> |
@endforeach
<a href="{{ url('contactus') }}">Contact Us</a>
Thanks a lot to all and enjoy the code :)
i don't speak english, so... sorry for possible errors.
You can use the IoC binding for this. In your middleware you can do this for binding $page instance:
\App::instance('mi_page_var', $page);
After, in your controller you call that instance:
$page = \App::make('mi_page_var');
The App::instance not re-instance the class, instead return the instance previusly binding.
I was able to add values to the Request-object with:
$request->attributes->set('key', 'value');
and get them back at a later point with:
$request->attributes->get('key');
This is possible because laravels Request extends symfonys Request which has the attribute "$attributes" of type ParameterBag that is intended to hold custom parameters.
I think this should be Best Practice to pass data to subsequent Middleware, Controllers or any other place where it's possible to access the Request-object.
Tested with Laravel 5.6, but probably also working with other versions.
참고URL : https://stackoverflow.com/questions/30212390/laravel-middleware-return-variable-to-controller
'developer tip' 카테고리의 다른 글
Aptana Studio 3에서 원격 호스트에 연결하는 방법 (0) | 2020.11.13 |
---|---|
ASP.MVC에서 여러 줄 Editor-For의 열과 행을 어떻게 지정합니까? (0) | 2020.11.13 |
두 개의 맥. (0) | 2020.11.13 |
python argparse를 접두사없이 상호 배타적 인 그룹 인수로 만드는 방법은 무엇입니까? (0) | 2020.11.13 |
didReceiveRemoteNotification이 호출되지 않음, iOS 10 (0) | 2020.11.13 |