How can allow the method in routes using laravel 5? - php

I'm trying to execute the method but it does not working. I know it is very basic and may be ask more time, but i didn't resolve.
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class LockController extends Controller {
/**
* Show the profile for the given user.
*
* #param int $id
* #return Response
*/
public function index()
{
return view('lock');
}
public function login()
{
return view('login');
}
}
?>
Route
Route::get('/lock', 'LockController#index');
Route::get('/lock', 'LockController#login');
This Route::get('/lock', 'LockController#index'); route working fine using this http://localhost/laravelDev/public/index.php/lock url but another route does not working properly and i'm getting this error NotFoundHttpException in RouteCollection.php line 161:. For login method i'm using this url http://localhost/laravelDev/public/index.php/lock/login.
I searched about it, i follow the instruction of this accepted answer but it does not work, can any one guide me where i'm wrong.

You can mention the required methods which will be handled in controller file(s) in routes.php file.
Example:
Route::get('url/of/the/resource', 'controllername#action'); (o handle 'GET' requests).
Route::post('url/of/the/resource', 'controllername#action'); (For 'POST' requests).
Details:
Route::get('/user/register', 'UserController#showRegistrationForm');
This indicates to show a registration from when given url (When GET request is made) is given like below:.
http://localhost/your_laravel_project_folder/user/register
Route::post('/user/register', 'UserController#handleUserRegistration');
This indicates to handle the registration from data when user submits the registration form. (When POST request is made).
class UserController extends Controller
{
public function showRegistrationForm()
{
return view('User.register');
}
public function handleUserRegistration()
{
$registerInput = Input::all();
var_dump($registerInput);
}
}

You have two identicals routes for different methods? I don't think that should work.
I could work if one was get and the other post.
Also, usualy, the url is would be http://localhost/lock or http://localhost/lock/login. The public/index.php shouldn't be necessaire.
Change the second route to this, pretty sure it'll work:
Route::get('/lock/login', 'LockController#login');

Related

Laravel 8 | Not hitting policy method

I am trying to define some policies in Laravel 8 which I cannot get to work, however I have the same project in Laravel 7 which seemingly works perfectly.
I am using the JSON API Specification package and it comes built in with Authorizers which allow me to run a policy on different methods.
I am trying to add a policy for the 'create' on all routes no matter what.
I have the following code:
public function create($type, $request)
{
$this->authorize('create', $type);
}
In this context and example, $type = 'App\Models\User' if I do a dd before that line I can confirm that I am hitting that method.
Inside of my AuthServiceProvider I have the following:
public function boot()
{
Gate::guessPolicyNamesUsing(function ($modelClass) {
return 'App\\Policies\\' . class_basename($modelClass) . 'Policy';
});
}
Which as said earlier, works perfectly in another project.
The following is my policy, as you can see it's very basic.
<?php
namespace App\Policies;
use App\Models\User;
class UserPolicy
{
public function create(User $user)
{
return true;
}
}
If I make a constructor in the policy class I can confirm that it is getting hit and I am getting inside of the policy which is why this is confusing me so much.
I have tried changing the name of the method in case it was something clashing with the naming convention but nothing seems to agree with it.
I have tried to dump composer just as a double check but again, no luck.
The issue with this is that there wasn't currently an authenticated user and although specified in the method parameters a user it was still failing.
When providing a guest route, you still need to add the parameter to the method but make it optional.
public function create(?User $user)
{
// do logic here
}
The documentation for this can be found at the following link: https://laravel.com/docs/master/authorization#guest-users

custom Shopware6 route gives "405 Method Not Allowed"

I created a shopware6 plugin which includes a frontend custom route which should be able to receive POST requests from ExactOnline.
But when I make some tests with Postman, I receive "405 Method Not allowed".
Here is my controller :
<?php
namespace Emakers\TransmissionPlugin\Controller;
//use Emakers\TransmissionPlugin\Controller\Frontend\Services\ExactRequirements;
use Shopware\Core\Framework\Routing\Annotation\RouteScope;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Shopware\Storefront\Controller\StorefrontController;
use Symfony\Component\Routing\Annotation\Route;
/**
* #RouteScope(scopes={"storefront"})
*/
class AccountsController extends StorefrontController
{
/**
* #Route("/accounts", name="frontend.accounts", options={"seo"="false"}, methods={"POST"})
*/
public function accounts()
{
die('ok boy');
$file = 'custom/plugins/TransmissionPlugin/Resources/webhooks/accountWebhook.txt';
}
}
When I replace the methods={"POST"} by methods={"GET"}, the same test request returns "ok boy" which is normal.
I had already created a plugin like this in Shopware5 and GET and POST requests were already working without doing anything special.
How to make POST requests ALLOW in my case on Shopware6?
Thanks !
You have limited the route to POST. When you call it from another Method then POST, it will result in Method not allowed error. Maybe you want to whitelist both GET and POST?
So change it to methods={"GET", "POST"}

Prevent redirect to homepage after invalid in Laravel

I'm developing a RESTful API with Laravel 5.3, so I'm testing some functions and request with my controllers. One thing I need to do is validate the request that my user sends before add a field in my database, so, I use a custom FormRequest to validate it.
When I tested my API in Postman and send my invalid request, response redirect me to homepage. After reading documentation, I found the following statement
If validation fails, a redirect response will be generated to send the
user back to their previous location. The errors will also be flashed
to the session so they are available for display. If the request was
an AJAX request, a HTTP response with a 422 status code will be
returned to the user including a JSON representation of the validation
errors.
How can I prevent this? Or there is a AJAX mode in Postman? Any suggestion?
Also this can be achieved without overriding any function. Laravel is built to support both Json & normal pages.
Please change your settings in postman and set Accept to application/json like below
Laravel is SMART ;-)
Your custom FormRequest extends Illuminate\Foundation\Http\FormRequest. Within is a function that performs the redirect called response(). Simply override this function within your custom FormRequest to change how invalid validations are responded to.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;
class CustomFormRequest extends FormRequest
{
/**
* Custom Failed Response
*
* Overrides the Illuminate\Foundation\Http\FormRequest
* response function to stop it from auto redirecting
* and applies a API custom response format.
*
* #param array $errors
* #return JsonResponse
*/
public function response(array $errors) {
// Put whatever response you want here.
return new JsonResponse([
'status' => '422',
'errors' => $errors,
], 422);
}
}
I faced same problem in Laravel 8. In your request class, you can override failedValidation method.
<?php
...
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class RegisterRequest extends FormRequest
{
...
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json(['errors' => $validator->errors()], 422));
}
...
}

Laravel: redirecting to a controller#store method redirects to the index instead

I am trying to redirect to PostsController#store but the page redirects to PostsController#index:
In routes.php:
Route::Resource('posts', 'PostsController');
Route::Resource('reviews', 'ReviewsController');
ReviewsController
class ReviewsController extends Controller {
public function store(Request $request) {
// (do a bunch of stuff)
return redirect(action('PostsController#store',[$request]));
}
}
PostsController
class PostsController extends Controller {
public function index() {
dd('Incorrectly redirects here');
}
public function store(Request $request, Post $post) {
dd('This is where I am trying to redirect to');
}
}
No error or exception occurs. However, once redirected, the url is:
http://localhost/laravel2devel/public/posts?POST%20/laravel2devel/public/reviews%20HTTP/1.1%0D%0AAccept:%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8%0D%0AAccept-Encoding:%20%20%20%20%20%20%20%20%20%20%20gzip,%20deflate%0D%0AAccept-Language:%20%20%20%20%20%20%20%20%20%20%20en-US,en;q=0.8%0D%0ACache-Control:%20%20%20%20%20%20%20%20%20%20%20%20%20max-age=0%0D%0AConnection:%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20keep-alive%0D%0AContent-Length:%20%20%20%20%20%20%20%20%20%20%20%20132%0D%0AContent-Type:%20%20%20%20%20%20%20%20%20%20%20%20%20%20application/x-www-form-urlencoded%0D%0ACookie:%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20XSRF-TOKEN=eyJpdiI6InhzN2JiK0FvYnIrUnVoeGZkcGNHOXc9PSIsInZhbHVlIjoiMFdrdnluNTdrR3l3OTlrZE9QSDA1WVwvalNoeDhHbG0wUXlvT0NBblRyWDNocFwvMExCZ0dqdVppbjR2M29SdnRmbWRDMkdRc042XC9ib3hrd2xZa1JCTmc9PSIsIm1hYyI6IjQ0ZmM4YTg4YmIxNTliMGY0MzI0OGMxMjMyZGM0ZDU4ZGM4MTVlMGM2NzVmZWNmM2YzZjI5YWU4OTJhOWM5MGYifQ%3D%3D;%20laravel_session=eyJpdiI6IjRCRThcLzdaR3ZaUUZJdTVQcmtVZk5BPT0iLCJ2YWx1ZSI6IlJYTlFaWk5WZEZQbHdkQzhtalhGbko0dnUzdzN0UjhOM2FLZUJQMkloNkMwdGRjc3VcL3lNUjBaXC9acktrUkxvRzZEWW4rVlY3Q0o2alB3VnJnNEZDdnc9PSIsIm1hYyI6ImIwMjRlMzIzYWYxNDI5NjEzYmFmZjljMjg4MmFkYzU1MTkzZDVkOWRjM2IwMzZlNTM1MTE2ZWExYTA3NmYyNzgifQ%3D%3D%0D%0AHost:%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20localhost%0D%0AOrigin:%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://localhost%0D%0AReferer:%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20http://localhost/laravel2devel/public/swords/1%0D%0AUpgrade-Insecure-Requests:%201%0D%0AUser-Agent:%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Mozilla/5.0%20%28Windows%20NT%206.1;%20WOW64%29%20AppleWebKit/537.36%20%28KHTML,%20like%20Gecko%29%20Chrome/48.0.2564.97%20Safari/537.36%0D%0A%0D%0A_token=DeQeCCA8e19IIsxGhouybXiqIFoAMLsQ6sgp5EMF&post_title=asdfdas&user_id=2&reviewable_id=1&reviewable_type=item&post_body=asdfdfas
If you use resource controller then, store() method is expected to be called with HTTP POST. If you redirect then it will use GET, so Laravel will call index() instead. See Laravel HTTP Resource Controllers documentation.
When you add a route as a resource it will handle the Restful requests to each methods.
A get request to the url will execute the index() method. For the store() method to execute a post request need to be given. store() method is to add the resource.
Please go through the resource controller documentation.
Im not clear about your question but my idea is if you wants store reviews for particular post just use your routes like this
Route::Resource('posts', 'PostsController');
Route::Resource('posts.reviews', 'ReviewsController');
then check the route:list then you will get the list of routes, i hope you have two tables then use foreign key you can archive your goal
i hope this is good tutorial for you LINK

Laravel Routing to non index method in controller

I am trying to create a route:
Route::get('/apply/submit', 'ApplyController#submit');
But I keep getting the standard Laravel error page.
My ApplyController:
class ApplyController extends BaseController {
public function index() {
return View::make('apply.apply', array('metaTitle' => 'China Aupair | Internships | Apply Online'));
}
public function submit() {
return 'yay!';
}
}
Which I don't understand because Route::get('/apply', 'ApplyController#index'); works as it should.
What am I doing wrong?
I think the problem is the method you access this page. You probably try to send form (using POST method) and you use get for the route. What you should do is change:
Route::get('/apply/submit', 'ApplyController#submit');
into
Route::post('/apply/submit', 'ApplyController#submit');
because you probably send a form and not run this route manually in browser using http://localhost/yourproject/apply/submit

Categories