App:Post object not found by the #ParamConverter annotation using symfony 4 - php

I want to have post by id or by slug, use ParamConverter but I find App error: Post object not found by the #ParamConverter annotation.knowing that I am a beginner at symfony and I followed a training.
I tried the route http://127.0.0.1:8000/blog/post/1
BlogController.php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Post;
/**
* #Route("/blog")
*/
class BlogController extends AbstractController {
/**
* #Route("/post/{id}", requirements={ "id" : "\d+" }, name="get_one_post_by_id", methods={"GET"})
* #ParamConverter("post", class="App:Post")
*/
public function postById($post){
return $this->json($post);
}
/**
* #Route("/post/{slug}", methods={"GET"})
* #ParamConverter("post", class="App:Post", options={"mapping": {"slug": "slug"}})
*/
public function postBySlug($post){
return $this->json($post);
}
/**
* #Route("/post/{id}", name="delete-post", methods={"DELETE"})
*/
public function destroy(Post $post){
$em = $this->getDoctrine()->getManager();
$em->remove($post);
$em->flush();
return $this->json(null, 204);
}

it should looks like:
use App\Entity\Post;
/**
* #Route("/post/{id}", requirements={ "id" : "\d+" }, name="get_one_post_by_id", methods={"GET"})
*/
public function postById(Post $post){
return $this->json($post);
}
that's all

Related

Symfony #ParamConverter only for active row

product_show:
path: /product/{id}
controller: App\Controller\ProductController::show
methods: GET
requirements:
id: \d+
<?php
declare(strict_types=1);
namespace App\Entity;
use App\Repository\ProductRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=ProductRepository::class)
*/
class Product
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
* #ORM\Column(type="integer")
*/
private int $id;
/**
* #ORM\Column(type="boolean", options={"default": true})
*/
private bool $active = true;
public function getId(): int
{
return $this->id;
}
public function active(): bool
{
return $this->active;
}
}
<?php
namespace App\Controller;
use App\Entity\Product;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
public function show(Product $product): Response
{
return $this->render('product/show.html.twig', [
'product' => $product,
]);
}
}
When $product->active() return false, I want to send 404 response.
But it should be done without adding an if in controller action.
Perhaps I should modify something in ParamConverter. How can I do this? How can I overwrite ParamConverter behavior?
You can fetch via an Expression and use a custom function in your repository.
For example:
class ProductController extends AbstractController
{
/**
* #Route("/product/{product_id}")
* #Entity("product", expr="repository.findOneActive(product_id)")
*/
public function show(Product $product): Response
{
return $this->render('product/show.html.twig', [
'product' => $product,
]);
}
}
And in your ProductRepository:
class ProductRepository
{
public function findOneActive($productId)
{
// your query here...
}
}

Laravel 5.5: Authorization Policy AccessDeniedHttpException This action is unauthorized

I created a policy for authorization, so I faced with this problem.
I have seen these solutions, but my problem didn't solve yet:
Solution 1
Solution 2
Solution 3
Here are the Codes:
Function used in ArticalesController Class:
public function show(Articale $articale)
{
$this->authorize('view', $articale);
return view('articales.show',compact('articale'));
}
ArticalePolicy Class:
<?php
namespace App\Policies;
use App\User;
use App\Articale;
use Illuminate\Auth\Access\HandlesAuthorization;
class ArticalePolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view the articale.
*
* #param \App\User $user
* #param \App\Articale $articale
* #return mixed
*/
public function view(User $user, Articale $articale)
{
return $user->id == $articale->user_id;
}
AuthServiceProvider Class:
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
Articale::class => ArticalePolicy::class,
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
}
}
Try with your model name as like this replace it with your AuthServiceProvider
replace
Articale::class => ArticalePolicy::class,
with
'App\Articale' => 'App\Policies\ArticalePolicy',

Automatic login after clicking on the link with the token (jrean/laravel-user-verification)

I use the "jrean/laravel-user-verification" package. When I click on the link with the token I want to redirect in my homepage and be already logged. How can I implement this? Thank you)
Laravel: 5.4
Package Version: 4.1
Solve this problem. Add to my register function (RegisterController) event:
public function register(VerificationRequest $request)
{
...
event(new Registered($user));
...
}
Сreate listener:
<?php
namespace App\Listeners;
use Illuminate\Auth\AuthManager;
use Jrean\UserVerification\Events\UserVerified;
/**
* Class UserVerifiedListener
* #package App\Listeners
*/
class UserVerifiedListener
{
/**
* #var AuthManager
*/
private $auth;
/**
* Create the event listener.
*
* #param AuthManager $auth
*/
public function __construct(AuthManager $auth)
{
$this->auth = $auth;
}
/**
* Handle the event.
*
* #param UserVerified $event
* #return void
*/
public function handle(UserVerified $event)
{
$this->auth->guard()->login($event->user);
}
}
And register it in :
app/Providers/EventServiceProvider.php
<?php
namespace App\Providers;
use App\Listeners\UserVerifiedListener;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Jrean\UserVerification\Events\UserVerified;
class EventServiceProvider extends ServiceProvider
{
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
UserVerified::class => [
UserVerifiedListener::class
],
];
/**
* Register any events for your application.
*
* #return void
*/
public function boot()
{
parent::boot();
//
}
public function register()
{
$this->app->bind(UserVerifiedListener::class, function () {
return new UserVerifiedListener(
$this->app->make('auth')
);
});
}
}

Call to undefined method App\Http\Controllers\SubscriptionController::getMiddleware()

I am calling the \prelaunchroute in my application and this is how it is defined in my routes.php:
`Route::get('/prelaunch', [ 'uses' => 'SubscriptionController#getReferrer', 'as' => 'subscriber.referral'], function () {
return view('prelaunch');
});`
But unfortunately, I am getting:
Call to undefined method App\Http\Controllers\SubscriptionController::getMiddleware()
This is a draft of my SubscriptionController code:
namespace App\Http\Controllers;
use App\Http\Manager\SubscriptionManager;
use Illuminate\Support\Facades\Request;
/**
* Class SubscriptionController
* #package App\Http\Controllers
*/
class SubscriptionController
{
/**
* #var \SubscriptionManager $subscriptionManager
*/
protected $subscriptionManager;
/**
* SubscriptionController constructor.
*/
//public function __construct(SubscriptionManager $subscriptionManager)
public function __construct(SubscriptionManager $subscriptionManager)
{
$this->subscriptionManager = $subscriptionManager;
}
/**
* #param Request $request
* #return void
*/
public function subscribe(Request $request)
{
$this->subscriptionManager->subscribeToList($request);
}
/**
* #param Request $request
* #return void
*/
public function unsubscribe(Request $request)
{
$this->subscriptionManager->unsubscribeFromList($request);
}
/**
* #return void
*/
public function getReferrer()
{
print_r(Input::all());
die;
$utm_source = \Input::get('utm_source');
return view('prelaunch');
}
}
Any thoughts on this one? Please bare in mind that I am fairly new to Laravel.
You forgot to extend the abstract controller:
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Manager\SubscriptionManager;
use Illuminate\Support\Facades\Request;
/**
* Class SubscriptionController
* #package App\Http\Controllers
*/
class SubscriptionController extends Controller
Try to extends Controller
/**
* Class SubscriptionController
* #package App\Http\Controllers
*/
class SubscriptionController extends Controller
{

Best Practices on namespaces : on Symfony, difference of perfs when using (sub)namespaces?

I'm building an API and I would ask something about using namespaces on a Symfony2 controller.
Is there a real difference doing :
<?php
namespace My\APIBundle\Controller;
use FOS\RestBundle\Controller\Annotations\View,
FOS\RestBundle\Controller\Annotations\Post,
FOS\RestBundle\Controller\Annotations\Get;
use [...]
class MyRestController extends Controller {
[...]
/**
* #View()
* #Get()
*/
public function getAction(Thing $thing) {
return $thing;
}
/**
* #View()
* #Post()
*/
public function postAction() {
}
or doing
<?php
namespace My\APIBundle\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use [...]
class MyRestController extends Controller {
[...]
/**
* #Rest\View()
* #Rest\Get()
*/
public function getAction(Thing $thing) {
return $thing;
}
/**
* #Rest\View()
* #Rest\Post()
*/
public function postAction() {
}
Would the alias load everything in the given namespace, losing perfs ?
Or will it load only annoted classes, unitary ?

Categories