I am new with PHP and Laravel.
I am using Laravel Framework version "laravel/framework": "5.4.*", and PHP 7.
I am building multilevel authentication.
I have been following https://www.youtube.com/watch?v=P8T3MjZPDdI
Alexander Curtis videos.
Error which I am getting is:
PHP Parse error: syntax error, unexpected '$login' (T_VARIABLE) in app/Exceptions/Handler.php on line 68
$login = 'admin.login';
[Mon May 8 20:53:30 2017] PHP Fatal error: Exception thrown without a stack frame in Unknown on line 0
Code is double check many times, from https://github.com/DevMarketer/multiauth_tutorial/archive/part_3.zip
I am using Laravel way to make auth, not any external package.
website /admin/login is showing blank page.
also webserver is php artisan serve.
I am stuck with this error.
<?php
namespace App\Exceptions;
use Exception; use Illuminate\Auth\AuthenticationException; use
Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
class Handler 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)
{
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
*/
Second part of code where added multilogin part
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(),0);
switch ($guard) {
case 'admin':
# code...
$login = 'admin.login';
break;
default:
# code...
$login ='login';
break;
}
return redirect()->guest(route($login));
}
}
You forgot to remove the default sublime text suggestions:
So remove the "# code ... " before your $login declaration.
switch ($guard) {
case 'admin':
*# code...*
$login = 'admin.login';
break;
default:
*# code...*
$login ='login';
break;
}
Related
I am building a laravel API and i need to be able to only accept requests of type 'application/json' when data is being posted. Any other content-types should return a 406 'Not Acceptable' response.
I am aware I could put in some middleware to check for this however I was wondering if there is a better way this could be accomplished?
Thanks
Use this middleware:
class WeWantJsonMiddleware
{
/**
* We only accept json
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->isMethod('post')) return $next($request);
$acceptHeader = $request->header('Accept');
if ($acceptHeader != 'application/json') {
return response()->json([], 406);
}
return $next($request);
}
}
(modification of https://stackoverflow.com/a/44453966/2311074)
And add it in App\Http\Kernel to $middleware to check for every post request. If you only want to check for API posts request, just put it in $middlewareGroups['api'].
Here's my two cents:
class JsonMiddleware
{
/**
* Accept JSON only
*
* #param Request $request
* #param Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$header = $request->header('Accept');
if ($header != 'application/json') {
return response(['message' => 'Only JSON requests are allowed'], 406);
}
if (!$request->isMethod('post')) return $next($request);
$header = $request->header('Content-type');
if (!Str::contains($header, 'application/json')) {
return response(['message' => 'Only JSON requests are allowed'], 406);
}
return $next($request);
}
}
Simple use middleware like this:
class OnlyAcceptJsonMiddleware
{
/**
* We only accept json
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
// Verify if POST request is JSON
if ($request->isMethod('post') && !$request->expectsJson()) {
return response(['message' => 'Only JSON requests are allowed'], 406);
}
return $next($request);
}
}
I used Postman to send request in my Laravel Api and I have a empty array to return. And I don't know why ?
My Route :
Route::middleware('auth:api')->group( function () {
Route::resource('reservations', 'ReservationController');
});
My reservationController :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ReservationCreateRequest;
use App\Repositories\ReservationRepository;
use App\Http\Resources\Reservation as ReservationResource;
class ReservationController extends BaseController
{
protected $entrepriseRepository;
public function __construct(ReservationRepository $reservationRepository)
{
$this->reservationRepository = $reservationRepository;
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$reservation = $this->reservationRepository->getById($id);
return $this->sendResponse(new ReservationResource($reservation), 'Reservation');
}
/**
* Update the specified resource in storage.
*
* #param Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$inputs = $request->all();
if (!$reservation = $this->reservationRepository->update($id, $inputs))
{
return $this->sendError('Impossible de mettre à jour', $request->errors(), 400);
}
return $this->sendResponse(new ReservationResource($reservation), 'Reservation mise à jour avec succès !' , 200);
}
}
if I return just a response with
return response($request->all());
I have a empty array...
The method
show($id)
works correctly...
Any suggestions someone ?
If you're sending PATCH request from postman, you need to send it with x-www-form-urlencoded as Laravel unfortunately gives empty request for form-data with PATCH request.
As a side note, you can't send files with x-www-form-urlencoded so if you have files in your request, you should send a POST request using form-data and _method: PATCH in the request body, Laravel will automatically treat it like a PATCH request.
I would like to know how can I set up my auth middleware in laravel 5.4.I am trying to set up the redirect route in
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->route('home');
}
return $next($request);
}
}
but there is no chages.
Can someone suggest a solution?
Your middleware probably works as is but you will still need to enable this. Information regarding registering middleware can be found here but in short:
// Within App\Http\Kernel Class...
protected $routeMiddleware = [
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];
This will name your middleware "guest" (which might already be enabled if you executed php artisan make:auth beforehand.
Then you will need to apply it this can be done in 1 of 2 ways.
On the route.
Directly
Route::get('admin/profile', 'AdminController#show')->middleware('guest');
With groups
Route::group(['middleware' => ['guest']], function () {//other routes});
I am planning to make a reverse geocoding based on the BazingaGeocoderBundle. A simple way to do that is write this simple code in the controller:
$result = $this->container
->get('bazinga_geocoder.geocoder')
->using('google_maps')
->reverse(48.79084170157100,2.42479377175290);
return $this->render("MinnAdsBundle:Motors:test.html.twig",
array('result'=>var_dump($result)));
Until here, things are going well.
My objective is to make the code nicer & resuable. So, I used this article to write my own GeocoderEventSubscriber as describer below:
<?php
namespace Minn\AdsBundle\Doctrine\Event;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Doctrine\ORM\Event\LifecycleEventArgs;
//use Geocoder\Provider\ProviderInterface;
use Bazinga\Bundle\GeocoderBundle\Geocoder\LoggableGeocoder;
/**
* Subscribes to Doctrine prePersist and preUpdate to update an
* the address components of a MotorsAds entity
*
* #author majallouli
*/
class MotorsAdsGeocoderEventSubscriber implements EventSubscriber {
protected $geocoder;
public function __construct(LoggableGeocoder $geocoder){
$this->geocoder = $geocoder;
}
/**
* Specifies the list of events to listen
*
* #return array
*/
public function getSubscribedEvents(){
return array(
'prePersist',
'preUpdate',
);
}
/**
* Sets a new MotorsAds's address components if not present
*
* #param LifecycleEventArgs $eventArgs
*/
public function prePersist(LifecycleEventArgs $eventArgs){
$motorsAds = $eventArgs->getEntity();
if($motorsAds instanceof \Minn\AdsBundle\Entity\MotorsAds){
if( !$motorsAds->getCountry()){
$em = $eventArgs->getEntityManager();
$this->geocodeMotorsAds($motorsAds,$em);
}
}
}
/**
* Sets an updating MotorsAds's address components if not present
* or any part of address updated
*
* #param PreUpdateEventArgs $eventArgs
*/
public function preUpdate(PreUpdateEventArgs $eventArgs){
$motorsAds = $eventArgs->getEntity();
if($motorsAds instanceof \Minn\AdsBundle\Entity\MotorsAds){
if( !$motorsAds->getCountry() ){
$em = $eventArgs->getEntityManager();
$this->geocodeMotorsAds($motorsAds,$em);
$uow = $em->getUnitOfWork();
$meta = $em->getClassMetadata(get_class($motorsAds));
$uow->recomputeSingleEntityChangeSet($meta, $motorsAds);
}
}
}
/**
* Geocode and set the MotorsAds's address components
*
* #param type $motorsAds
*/
private function geocodeMotorsAds($motorsAds,$em){
$result = $this->geocode
->using('google_maps')
->reverse($motorsAds->getLat(),$motorsAds->getLng());
$motorsAds->setCountry(
$em->getRepository("MinnAdsBundle:Country")->findCountryCode($result['countryCode']));
}
}
After that, I declared my EventSubscriber as a service:
services:
# ...
geocoder_motorsads.listener:
class: Minn\AdsBundle\Doctrine\Event\MotorsAdsGeocoderEventSubscriber
arguments: [#bazinga_geocoder.geocoder] # almost sure that the error is here!!
tags:
- { name: doctrine.event_subscriber }
Actually, I get this error:
ContextErrorException: Notice: Undefined property: Minn\AdsBundle\Doctrine\Event\MotorsAdsGeocoderEventSubscriber::$geocode in /home/amine/NetBeansProjects/tuto/src/Minn/AdsBundle/Doctrine/Event/MotorsAdsGeocoderEventSubscriber.php line 78
I am almost sure that error is in the declaration of arguments of the EventSubscriber. Is it #bazinga_geocoder.geocoder?
Thank you for your help!
Your property is $this->geocoder but you're calling $this->geocode, you're spelling it wrong.
With the introduction of Zend_Rest_Route in Zend Framework 1.9 (and its update in 1.9.2) we now have a standardized RESTful solution for routing requests. As of August 2009 there are no examples of its usage, only the basic documentation found in the reference guide.
While it is perhaps far more simple than I assume, I was hoping those more competent than I might provide some examples illustrating the use of the Zend_Rest_Controller in a scenario where:
Some controllers (such as indexController.php) operate normally
Others operate as rest-based services (returning json)
It appears the JSON Action Helper now fully automates and optimizes the json response to a request, making its use along with Zend_Rest_Route an ideal combination.
Appears it was rather simple. I've put together a Restful Controller template using the Zend_Rest_Controller Abstract. Simply replace the no_results return values with a native php object containing the data you want returned. Comments welcome.
<?php
/**
* Restful Controller
*
* #copyright Copyright (c) 2009 ? (http://www.?.com)
*/
class RestfulController extends Zend_Rest_Controller
{
public function init()
{
$config = Zend_Registry::get('config');
$this->db = Zend_Db::factory($config->resources->db);
$this->no_results = array('status' => 'NO_RESULTS');
}
/**
* List
*
* The index action handles index/list requests; it responds with a
* list of the requested resources.
*
* #return json
*/
public function indexAction()
{
// do some processing...
// Send the JSON response:
$this->_helper->json($this->no_results);
}
// 1.9.2 fix
public function listAction() { return $this->_forward('index'); }
/**
* View
*
* The get action handles GET requests and receives an 'id' parameter; it
* responds with the server resource state of the resource identified
* by the 'id' value.
*
* #param integer $id
* #return json
*/
public function getAction()
{
$id = $this->_getParam('id', 0);
// do some processing...
// Send the JSON response:
$this->_helper->json($this->no_results);
}
/**
* Create
*
* The post action handles POST requests; it accepts and digests a
* POSTed resource representation and persists the resource state.
*
* #param integer $id
* #return json
*/
public function postAction()
{
$id = $this->_getParam('id', 0);
$my = $this->_getAllParams();
// do some processing...
// Send the JSON response:
$this->_helper->json($this->no_results);
}
/**
* Update
*
* The put action handles PUT requests and receives an 'id' parameter; it
* updates the server resource state of the resource identified by
* the 'id' value.
*
* #param integer $id
* #return json
*/
public function putAction()
{
$id = $this->_getParam('id', 0);
$my = $this->_getAllParams();
// do some processing...
// Send the JSON response:
$this->_helper->json($this->no_results);
}
/**
* Delete
*
* The delete action handles DELETE requests and receives an 'id'
* parameter; it updates the server resource state of the resource
* identified by the 'id' value.
*
* #param integer $id
* #return json
*/
public function deleteAction()
{
$id = $this->_getParam('id', 0);
// do some processing...
// Send the JSON response:
$this->_helper->json($this->no_results);
}
}
great post, but I would have thought the Zend_Rest_Controller would route the request to the right action with respect to the HTTP method used. It'd be neat if a POST request to http://<app URL>/Restful would automatically _forward to postAction for example.
I'll go ahead and provide another strategy below, but maybe I'm missing the point behind Zend_Rest_Controller ... please comment.
My strategy:
class RestfulController extends Zend_Rest_Controller
{
public function init()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
}
public function indexAction()
{
if($this->getRequest()->getMethod() === 'POST')
{return $this->_forward('post');}
if($this->getRequest()->getMethod() === 'GET')
{return $this->_forward('get');}
if($this->getRequest()->getMethod() === 'PUT')
{return $this->_forward('put');}
if($this->getRequest()->getMethod() === 'DELETE')
{return $this->_forward('delete');}
$this->_helper->json($listMyCustomObjects);
}
// 1.9.2 fix
public function listAction() { return $this->_forward('index'); }
[the rest of the code with action functions]