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.
Related
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);
I have an application run with Symfony 3.4 with MySql and I get a error: 'The EntityManager is closed'. My application running two ways:
1 - A Console application thats is called by a sh script every time. This console app make many inserts in a database table.
2 - A HTTP Route that also insert in same table.
When de console app is running in background if i call the http route i get the error 'The EntityManager is closed'. If I stop de backgroud app the http route works. It's as if the two apps console and http use the same instance EntityManager.
My code:
I Create a service called AbstractRepositoryService. All of my services that manage repositories should extend.
<?php
abstract class AbstractRepositoryService
{
/**
*
* #var EntityManagerIntergace - $em
*/
protected $em;
/**
*
* #param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em) {
$this->em = $em;
}
/**
*
*
* #param String
*
* #return #mixed
*
* #throws RuntimeException
*/
public function __call($method, $args) {
$repository = $this->em->getRepository(static::ENTITY);
if (!method_exists($repository, $method)) {
throw new RuntimeException(
sprintf("Method '%s' not found.", $method),
500
);
}
try {
return call_user_func_array(array($repository, $method), $args);
} catch(Exception $e) {
throw new Exception($e->getMessage(), 500);
}
}
}
My UserRepositoryService where the exception is thrown in the flush method
<?php
final class UserRepositoryService extends AbstractRepositoryService
{
/**
*
* #const String
*/
const ENTITY = 'AppBundle\\Entity\\User';
/**
*
* #param User
*/
public function insert(User $user) {
try {
$this->em->persist($user);
$this->em->flush($user);
} catch (Exception $e) {
throw new Exception($e->getMessage(), 500);
}
}
}
And finaly my service declaration:
app.services.user_repository_service:
public: true
class: AppBundle\Services\UserRepositoryService
arguments:
- '#doctrine.orm.entity_manager'
Solved!
I created a method that generate new EntityManager before insert and works now.
protected function createNewEntityManager() {
return $this->em->create(
$this->em->getConnection(),
$this->em->getConfiguration(),
$this->em->getEventManager()
);
}
And in insert:
public function insert(Crawler $crawler) {
try {
$this->createNewEntityManager();
$this->em->persist($crawler);
$this->em->flush($crawler);
$this->em->close();
} catch (Exception $e) {
throw new Exception($e->getMessage(), 500);
}
}
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);
}
I have recently installed Ratchet on my laravel installation to enable push services over sockets.
This is what my SocketController class looks like (note: it does NOT extend controller)
class SocketController implements WampServerInterface
{
/**
* A lookup of all the topics clients have subscribed to
*/
protected $subscribedTopics = array();
public function onSubscribe(ConnectionInterface $conn, $topic) {
echo"\n SUBSCRING TOPIC: $topic";
echo " hi \n";
try {
JWTAuth::parseToken("okay");
} catch (TokenExpiredException $e) {
echo "hi" ;
} catch (TokenInvalidException $e) {
echo "hi" ;
} catch (JWTException $e) {
echo "hi" ;
}
catch(\Exception $q){
echo $q;
}
$this->subscribedTopics[$topic->getId()] = $topic;
}
/**
* #param string JSON'ified string we'll receive from ZeroMQ
*/
public function onBlogEntry($entry) {
$entryData = json_decode($entry, true);
// If the lookup topic object isn't set there is no one to publish to
if (!array_key_exists($entryData['category'], $this->subscribedTopics)) {
return;
}
$topic = $this->subscribedTopics[$entryData['category']];
// re-send the data to all the clients subscribed to that category
$topic->broadcast(rand(5,666666));
}
public function onUnSubscribe(ConnectionInterface $conn, $topic) {
}
public function onOpen(ConnectionInterface $conn) {
echo"open";
}
public function onClose(ConnectionInterface $conn) {
echo "close";
}
/* The rest of our methods were as they were, omitted from docs to save space */
/**
* If there is an error with one of the sockets, or somewhere in the application where an Exception is thrown,
* the Exception is sent back down the stack, handled by the Server and bubbled back up the application through this method
* #param ConnectionInterface $conn
* #param \Exception $e
* #throws \Exception
*/
function onError(ConnectionInterface $conn, \Exception $e)
{
// TODO: Implement onError() method.
}
/**
* An RPC call has been received
* #param \Ratchet\ConnectionInterface $conn
* #param string $id The unique ID of the RPC, required to respond to
* #param string|Topic $topic The topic to execute the call against
* #param array $params Call parameters received from the client
*/
function onCall(ConnectionInterface $conn, $id, $topic, array $params)
{
// TODO: Implement onCall() method.
}
/**
* A client is attempting to publish content to a subscribed connections on a URI
* #param \Ratchet\ConnectionInterface $conn
* #param string|Topic $topic The topic the user has attempted to publish to
* #param string $event Payload of the publish
* #param array $exclude A list of session IDs the message should be excluded from (blacklist)
* #param array $eligible A list of session Ids the message should be send to (whitelist)
*/
function onPublish(ConnectionInterface $conn, $topic, $event, array $exclude, array $eligible)
{
// TODO: Implement onPublish() method.
}
I am using the JWT library, and just to check,have the line
JWTAuth::parseToken("okay");
But that line throws an error:
exception 'RuntimeException' with message 'A facade root has not been
set.'
How do I include JWT auth into my own class ?
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));
}