Laravel localization in 404 page - php

Hello I have an issue with laravel localization
I've made language switcher and currently selected language doesn't work on 404 pages (it works if I return abort(404) in controller manualy), it always shows content on default locale defined in config/app.php
My middleware code
<?php
namespace App\Http\Middleware;
use Closure;
class SetLanguageCookie
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->hasCookie('language')) {
$cookie = $request->cookie('language');
app()->setLocale($cookie);
return $next($request);
} else {
$response = $next($request);
$response->withCookie(cookie()->forever('language', 'en'));
return $response;
}
}
}
Any ideas how can I make this working? So all automaticaly shown 404 pages show content in currently selected language?

If you have default error handling, look for this file:
app\Exceptions\Handler.php
Change the render method to something like this:
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if($e instanceof NotFoundHttpException)
{
if(\Request::hasCookie('language')) {
$cookie = \Request::cookie('language');
app()->setLocale($cookie);
//.... etc
}
}
return parent::render($request, $e);
}

Fixed it with help of #ArthurSamarcos
app/Exceptions/Handler.php
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if($request->hasCookie('language')) {
// Get cookie
$cookie = $request->cookie('language');
// Check if cookie is already decrypted if not decrypt
$cookie = strlen($cookie) > 2 ? decrypt($cookie) : $cookie;
// Set locale
app()->setLocale($cookie);
}
if($e instanceof NotFoundHttpException) {
return response()->view('errors.404', [], 404);
}
return parent::render($request, $e);
}

Related

Laravel Target class [PagesController] does not exist error in Handler

My final goal is to use data from the database to display on the 404 page.
I have added the following code to my Handler.php in render method:
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('errors.' . '404', [], 404);
}
}
Content of errors.404.blade.php is only "test".
I have checked the name of the PagesController file, and it is capitalized as it should. I've also tried to empty the cache with Artisan::call('route:clear');, Artisan::call('cache:clear');, Artisan::call('cache:clear');, and Artisan::call('view:clear'); (I don't have access to the terminal directly).
Any help is appreciated.
Thanks.
Edit: This is the full handler file:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\App;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* #var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* #param \Exception $exception
* #return void
*
* #throws \Exception
*/
public function report(Exception $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Symfony\Component\HttpFoundation\Response
*
* #throws \Exception
*/
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('errors.' . '404', [], 404);
}
}
return parent::render($request, $exception);
}
}
try this code
if ($exception instanceof UnauthorizedException) {
return response()->view('errors.403', [], 403);
}
return parent::render($request, $exception);

How can I prevent a ParseError in Symfony 4?

src/Controller/DataTableController.php
<?php
use DataTables\DataTablesInterface;
/**
* Symfony 3.4 and above
*
* #Route("/users", name="users")
*
* #param Request $request
* #param DataTablesInterface $datatables
* #return JsonResponse
*/
public function usersAction(Request $request, DataTablesInterface $datatables): JsonResponse
{
try {
// Tell the DataTables service to process the request,
// specifying ID of the required handler.
$results = $datatables->handle($request, 'users');
return $this->json($results);
}
catch (HttpException $e) {
// In fact the line below returns 400 HTTP status code.
// The message contains the error description.
return $this->json($e->getMessage(), $e->getStatusCode());
}
}
/**
* Symfony 3.3 and below
*
* #Route("/users", name="users")
*
* #param Request $request
* #return JsonResponse
*/
public function usersAction(Request $request): JsonResponse
{
try {
/** #var \DataTables\DataTablesInterface $datatables */
$datatables = $this->get('datatables');
// Tell the DataTables service to process the request,
// specifying ID of the required handler.
$results = $datatables->handle($request, 'users');
return $this->json($results);
}
catch (HttpException $e) {
// In fact the line below returns 400 HTTP status code.
// The message contains the error description.
return $this->json($e->getMessage(), $e->getStatusCode());
}
}
I get the error message:
The structure for a class, (not related to Symfony) is
class MyClassController() {
public function myMethodAction() {
}
}
There is not way to avoid a parse error because this is just not valid syntax of PHP.

how to exce middleware , when the laravel exception

I use laravel5.5 for a web program. But when the program is exception, the middleware don't work.
what should i do for it?
my middleware code is list:
namespace App\Http\Middleware;
use Closure;
class ApiException
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$env = config('app.env');
$statusCode = $response->getSatusCode();
if ($statusCode >= 500 && $env != 'dev') {
$response->setContent(['error' => 'Internal Server Error']);
}
return $next($request);
}
}
thank you help me !
There is no way you can do that in Middlewares. You can control exceptions in your app\Exceptions\Handler.php instead.
In middleware can't but in Exception/Handler can..
anytime the exception occurred.. it not entered the middleware, it entered Exception/Handler.php..
in render method
public function render($request, Exception $exception)
{
if ($exception->getCode() >= 500 ||) {
//return redirect()->route(); do something here
}
return parent::render($request, $exception);
}

Laravel request validation throwing HttpResponseException in version 5.2

I'm trying to update Laravel from version 5.1 to 5.2 in my project, I have followed this upgrade guide from the documentation, but now I'm getting this HttpResponseException when a validation fails
* Handle a failed validation attempt.
*
* #param \Illuminate\Contracts\Validation\Validator $validator
* #return mixed
*
* #throws \Illuminate\Http\Exception\HttpResponseException
*/
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException($this->response(
$this->formatErrors($validator)
));
}
In 5.1, the framework redirected to the previous url automatically with the validation errors.
This is my validation request
namespace domain\funcao\formRequest;
use autodoc\Http\Requests\Request;
class StoreFuncaoRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'codigo' => 'required|max:255|unique:funcao,codigo,'.$this->input('id').',id,deleted_at,NULL',
'nome' => 'required|max:255|unique:funcao,nome,'.$this->input('id').',id,deleted_at,NULL'
];
}
}
I have already updated my Exceptions Handler according to the guide
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
\Illuminate\Auth\Access\AuthorizationException\AuthorizationException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Foundation\ValidationException\ValidationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
];
...
}
Did someone had this problem??
I found the cause for this error, I was calling PrettyPageHandler from Whoops manually in my Exception Handler class.
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* #var array
*/
protected $dontReport = [
\Illuminate\Auth\Access\AuthorizationException\AuthorizationException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Foundation\ValidationException\ValidationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
];
...
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// I just needed to remove this call to get rid of the problem
if (config('app.debug'))
{
return $this->renderExceptionWithWhoops($e);
}
return parent::render($request, $e);
}
/**
* Render an exception using Whoops.
*
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
protected function renderExceptionWithWhoops(Exception $e)
{
$whoops = new \Whoops\Run;
$whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler());
return new \Illuminate\Http\Response(
$whoops->handleException($e),
$e->getStatusCode(),
$e->getHeaders()
);
}
}
I'm still using Whoops, but now automatically through Laravel Exceptions
This was the first question I came across when I had this problem although for me it was with Sentry not Whoops.
Here's a couple of exceptions and how I dealt with them:
public function render($request, Exception $e)
{
if ($e instanceof TokenMismatchException) {
return redirect()->back()->withInput()->with('error', 'Your Session has Expired');
}
if ($e instanceof HttpResponseException) {
return $e->getResponse();
}
return response()->view('errors.500', [
'sentryID' => $this->sentryID,
], 500);
}
I handle the HttpResponseException by simply returning the response the same way the ExceptionHandler class does.
All you have to do is, just write your business logics inside the protected failedValidation() inside your custom FormRequest class like follows
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
/**
* [failedValidation [Overriding the event validator for custom error response]]
* #param Validator $validator [description]
* #return [object][object of various validation errors]
*/
public function failedValidation(Validator $validator) {
// write your business logic here otherwise it will give same old JSON response
throw new HttpResponseException(response()->json($validator->errors(), 422));
}

RESTful API response in Laravel 5

I'm building RESTful API with Laravel. My API always returns JSON. What I would like to do, is keeping response logic at one place. Here's how I do it right now in API controller, which is pointed to by Route::controller(). Funny and ultra-useful example coming:
public function getDouble($number) {
try {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
$response = $number * 2;
$status = 200;
}
catch (HttpException $exception) {
$response = $exception->getMessage();
$status = $exception->getStatusCode();
}
return response()->json($response, $status);
}
In this example, my API route would be for example /double/13 accessed by GET method. The problem is that I repeat this try ... catch block in each method. I would like my API methods to be like:
public function getDouble($number) {
if (!is_numeric($number)) {
throw new HttpException(400, 'Invalid number.');
}
return $number;
}
And then, catch those exceptions and form JSON in another place. What is the best approach here in terms of good application architecture?
Response on Exception
You could do this by handling the exception in App\Exceptions\Handler.
You could do it in the render method, likeso :
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $e
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if($e instanceof HttpException) {
return response()->json($e->getMessage(), $e->getStatusCode());
}
return parent::render($request, $e);
}
Success Response
There are several ways to do this but I guess Middleware would be the best suited one right.
Create a middleware (say, ApiResponseFormatterMiddleware)
In your 'App\Http\Kernel', add it to $routeMiddleware array.
Apply it to the api routes, response to which you want to parse.
You could do something in the lines of :
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
return response()->json($response->getOriginalContent());
}
Ofcourse, you need to change a bit of logic to parse the content the way you want it, but skeleton remains the same.

Categories