Controller return `false` while DashboardController return `true` - laravel

I am running laravel 6.11
and by default we have this
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
dd(Auth::check());
}
}
and I have defined my controller like this,
class DashboardController extends Controller
{
/**
* Display dashboard
*
* #return \Illuminate\Http\Response
*/
public function index()
{
dd(Auth::check());
}
}
Now the user successfully login,
and visiting same page, dashboard at different time
Controller return false while DashboardController return true
Why is that?

As of Laravel 5.3, you can't access the session (including Auth) in the controller constructor. You can, however, define a middleware closure in the constructor that will have access to the session.
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
$this->middleware(function ($request, $next) {
dd(Auth::check());
});
}
}

Related

How to trigger event handler when session timeout in laravel?

Is there a way to call event handler when session is up? below is my eventhandler for logout.
class AuthLogoutEventHandler
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct($user)
{
$this->user = $user;
}
}
Already registered my Eventhandler and listener in EventServiceProvider.php

"$request->ajax()" why is not working in laravel middleware?

$request->ajax(); is not working in laravel 5.5 i want to hendel session redirection for ajax
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Closure;
use Session;
//use Request;
class IsLogin
{
public function handle(Request $request, Closure $next)
{
if($request->ajax())
{
return response()->json(['Session_error'=>'Session Expired'], 401);
//throw new AuthenticationException('Unauthenticated');
}
}

Can #RequestMapping in Springboot be omitted?

I want to make the method name be the 'value' of #RequestMapping.
That means how to make the code1 be the code2?
//Code1
#RequestMapping("hello")
public Object hello() {
//...
}
//Code2
public Object hello() {
//...
}
-----add more to make it clear ---2019-2-27 15:47:50
TO make it clear, I want to get two API user/hello, user/bye by code:
#RestController
#RequestMapping(value="/user")
public class UserController {
//no requestmapping annotation here, that is what I say 'omitted'
public object hello() {
// your code
}
//no requestmapping annotation here
public object bye() {
// your code
}
```
Suppose you have one common URL in your request.
Let's say you have /user in your all requests then instead of your writing /user in all your method, you can use #RequestMapping(value="/user") as below. You can have multiple methods inside your controller
#RestController
public class UserController {
#RequestMapping(value="/user/hello",method=RequestMethod.yourMethod)
public object hello() { // your code
}
#RequestMapping(value="/user/bye",method=RequestMethod.yourMethod)
public object bye() { // your code
}
Solution:
#RestController
#RequestMapping(value="/user")
public class UserController {
#RequestMapping(value="/hello",method=RequestMethod.yourMethod)
public object hello() { // your code
}
#RequestMapping(value="/bye",method=RequestMethod.yourMethod)
public object bye() { // your code
}

How can I register custom error handler in laravel 5?

I'm developing a Laravel package, have a service provider with views and everything, but I need to have custom error messages. How can I register custom error handler in my service provider?
You can register custom handler by binding it with Laravel's exception handler class on service provider.
Create Custom Handler
First you have to create custom exception handler class.
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class CustomHandler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* #param \Exception $exception
* #return void
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if ($exception instanceof NotFoundHttpException) {
return response()->view('errors.404', [], 404);
}
return parent::render($request, $exception);
}
/**
* Convert an authentication exception into an unauthenticated response.
*
* #param \Illuminate\Http\Request $request
* #param \Illuminate\Auth\AuthenticationException $exception
* #return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest('login');
}
}
Register Your Handler
Now register the class on your AppServiceProvider
<?php
namespace App\Providers;
use App\Exceptions\CustomHandler;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
/**
* Do not forget to import them before using!
*/
$this->app->bind(
ExceptionHandler::class,
CustomHandler::class
);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
}
}
For more information check this blog http://blog.sarav.co/registering-custom-exception-handler-laravel-5/
Since Laravel 8.0 you can use the built-in renderable and reportable methods on the Handler class that is bound to the ExceptionHandler contract (https://laravel.com/docs/8.x/errors#rendering-exceptions).
So for example:
<?php
namespace App\Providers;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
/** #var ExceptionHandler $exceptionHandler */
$exceptionHandler = resolve(ExceptionHandler::class);
$exceptionHandler->renderable(function (NotFoundHttpException $e, $request) {
if ($request->wantsJson()) {
return response()->json([
'success' => false,
'message' => 'Endpoint not found'
], 404);
}
});
}
}

MVC3 Controller not recongnising base controller with Ninject dependency

I've hooked up Ninject (correctly) to bind NLog. Here is my RegisterService method in my NinjectMVC3.cs
kernel.Bind<ILogger>().To<NLogger>();
I'm trying to port over to PetaPoco and have created a base controller here:
public class BaseController : Controller
{
protected PetaPoco.Database _database;
protected ILogger _logger;
protected MemberRepository _members;
public BaseController(ILogger logger)
{
_database = new PetaPoco.Database("TalentSiteConnection");
_members = new MemberRepository(_database);
_logger = logger;
}
}
When I inherit my base controller like so:
public class TestController : BaseController
{
public ActionResult Index()
{
TestViewModel model = new TestViewModel();
model.Member = _members.Single<Member>(2579);
return View("Index", model);
}
}
and try to run a build I'm getting a
'BaseController' does not contain a constructor that takes 0 arguments
What am I doing wrong? I thought Ninject would resolve the dependency on the constructor?
.
TestController needs that ctor...
public class TestController : BaseController
{
public TestController(ILogger logger) : base(logger) {}
...this has nothing to do with NInject. If you added a parameterless ctor to BaseController and left your TestController as is, you wouldn't get the logger injection.

Resources