Redirect to laravel without return

I have this blogController, the create function is as follows.

public function create() { if($this->reqLogin()) return $this->reqLogin(); return View::make('blogs.create'); } 

In BaseController, I have this function that checks if a user is registered.

  public function reqLogin(){ if(!Auth::check()){ Session::flash('message', 'You need to login'); return Redirect::to("login"); } } 

This code works fine, but this is not what I need, I want my create function to be next.

 public function create() { $this->reqLogin(); return View::make('blogs.create'); } 

Can I do it?

Also, can I set authentication rules, as in Yii , at the top of the controller.

+6
source share
2 answers

You must put the check in the filter, and then allow the user to only go to the controller if they are logged in first.

Filter

 Route::filter('auth', function($route, $request, $response) { if(!Auth::check()) { Session::flash('message', 'You need to login'); return Redirect::to("login"); } }); 

Route

 Route::get('blogs/create', array('before' => 'auth', 'uses' => ' BlogsController@create ')); 

controller

 public function create() { return View::make('blogs.create'); } 
+2
source

Besides organizing your code to fit the best Laravel architecture, there is a little trick that you can use when returning a response is not possible and redirecting is absolutely necessary.

The trick is to call \App::abort() and pass the code and headers. This will work in most cases (excluding, in particular, kinds of blades and __toString() methods.

Here is a simple function that will work everywhere , no matter what, while maintaining its shutdown logic.

 /** * Redirect the user no matter what. No need to use a return * statement. Also avoids the trap put in place by the Blade Compiler. * * @param string $url * @param int $code http code for the redirect (should be 302 or 301) */ function redirect_now($url, $code = 302) { try { \App::abort($code, '', ['Location' => $url]); } catch (\Exception $exception) { // the blade compiler catches exceptions and rethrows them // as ErrorExceptions :( // // also the __toString() magic method cannot throw exceptions // in that case also we need to manually call the exception // handler $previousErrorHandler = set_exception_handler(function () { }); restore_error_handler(); call_user_func($previousErrorHandler, $exception); die; } } 

Usage in PHP:

 redirect_now('/'); 

Usage per click:

 {{ redirect_now('/') }} 
+8
source

Source: https://habr.com/ru/post/974582/


All Articles