Forbidden error when creating nested controller object laravel - php

I'm folowing a tutorial on https://laracasts.com/series/laravel-5-fundamentals
then I started digging into nested controllers from this tutorial https://www.flynsarmy.com/2015/02/creating-a-basic-todo-application-in-laravel-5-part-4/
I've got a similar logic Project which has one hypothesis.
So I've setup my nested routes
Route::resource('project','ProjectsController');
Route::resource('project.hypothesis','HypothesisController');
Then created a form for adding a hypothesis to a Project
{!! Form::model(new App\Hypothesis, ['route' => ['project.hypothesis.store', $project->id]]) !!}
#include ('hypothesis.form',['submitButtonText'=>'create']);
{!! Form::close() !!}
I also created a HyphothesisRequest class with basic validation rules
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class HyphothesisRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'description' =>'required'
];
}
}
Now according to the above tutorials in my controller i've got
public function store(Project $project, HyphothesisRequest $request)
{
$this->validate($request);
$h = new Hypothesis;
$h->description = $request->description;
$h->project_id = $project->id;
$h->save();
return Redirect::route('project.show', $project->id);
}
The problem is that when the HyphothesisRequest $request is passed as an argument I get an forbidden page from laravel. When I remove this it goes to the desired page but without validation.
I'm at the basic level of this so please be patient :)

Try change
public function authorize()
{
return false;
}
to
public function authorize()
{
return true;
}

Related

Laravel validation - how to return back with errors from Request on fail?

On validation fail, I have 2 situations
one when I display a new error page (this is how it was done before in the app)
I have a form and I redirect back with input (my problem)
The app is catching the ValidationException in the exceptions Handler - so there is no back with errors for me if a request fails.
Now, I need to return back to the input with errors - from the request class, before it throws the standard ValidationException.
How do I do that from the request class pls?
The code is very basic
I have some rules...
I imagine I need a hook like - validationFailed().. in the request class?
Edit: - not API - regular monolithic PHP
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Auth;
class LocationCodeRequest extends FormRequest
{
/**
* 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()
{
$user = Auth::user();
return [
'new_location_code' => 'required|string|max:255|exists:xxx,code',
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'new_location_code.not_in' => 'xxx',
'new_location_code.exists' => 'yyy',
];
}
//I need something like this
public function validationFailed()
{
return redirect()->back()->withErrors($this->validator)->withInput();;
}
}
Normally the FormRequest Class will redirect back to the Form Page with inputs and validation errors. That's the default functionality.
public function validationFailed() {
return redirect()->back()->withErrors($this->validator)->withInput();;
}
You don't require the above code if you are passing the FormRequest class in the POST call of the Form like so
use App\Http\Requests\LocationCodeRequest;
public function store(LocationCodeRequest $request) {
// Code after validation
}
You can try by adding this in the LocationCodeRequest file.
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
protected function failedValidation(Validator $validator) {
// Add redirection here. Errorbag and Inputs shud be available in session or can be passed here
//throw new HttpResponseException(response()->json($validator->errors(), 422));
}

Laravel custom form requests not validating

I'm have created a custom form request in my laravel 5.6 something like this:
<?php
namespace Noetic\Plugins\blog\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePostRequest extends FormRequest
{
/**
* 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 [
];
}
}
When I do not place anything in rules, I get the controllers working, and when I put any rule inside suppose I put
return [
'title' => 'required',
'body' => 'required',
];
It works until it gets validated true, I mean if title and body is passed it gets validated, but when I don't send any data for title or body I'm not getting errors as response, I see the home page belonging to web middleware, I want to return the error data as response.
My controller is something like this:
public function store( StorePostRequest $request )
{
if ($request->fails()) {
return $this->errorResponse($request->errors()->all());
}
$data = $request->only('title', 'body');
$post = Post::create($data);
return response()->json(['post'=> $post ],200);
}
Help me out with these. Thanks
In your controller function you don't need to catch the validation just try with success path.
Handler will handle your validation
public function store( StorePostRequest $request )
{
$data = $request->only('title', 'body');
$post = Post::create($data);
return response()->json(['post'=> $post ],200);
}
In your Handler
use Illuminate\Validation\ValidationException;
if ($exception instanceof ValidationException)
{
return response($exception->errors())->header('Content-Type', 'application/json');
}
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
after that
protected function failedValidation(Validator $validator) {
throw new HttpResponseException(response()->json($validator->errors(), 422));
}

Laravel 5.2 Form Validation Request

I am currently trying to validate a 'Create Articles' form in my first Laravel application and I am having some problems. I have been following along with a tutorial that is meant for Laravel 5, however, and I am running Laravel 5.2 on this project. I have read through the documentation for Validation in Laravel 5.2 and I have asked another Laravel Developer but we just cannot seem to figure it out.
CreateArticleRequest.php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class CreateArticleRequest 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 [
'title' => 'required|min:3',
'body' => 'required',
'published_at' => 'required|date'
];
}
}
create() and store() from ArticlesController.php
public function create()
{
return view('articles.create');
}
public function store(CreateArticleRequest $request)
{
Article::create($request->all());
return redirect('articles');
}
Where I am trying to load the errors in create.blade.php
{{ dd($errors->all()) }}
#if ($errors->any())
<ul class="alert alert-danger">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
The ErrorBag that is returned from $errors is completely empty and doesn't seem to want to populate. I have also tried to use the Validator $validator but I cannot seem to get that to even load in.
Any help would be greatly appreciated.
Put all your routes inside to enable Session errors sharing:
Route::group(['middleware' => ['web']], function () {
// Here comes your routes
});
More details: Custom request not calling controller method on form validation success

Laravel 5.1 - How to send parameter to authorize() function

I'm making a real estate application. When the user opens one of his published properties to edit, in the edit page, the form opens like this:
{!! Form::model($property, ['method'=>'PUT', 'route'=>['property.update', 'id'=>$property->id], 'files'=>true]) !!}
As you can see, in the 'route' array I'm sending the named route and the id of the property to be edited. But how do I access that $id in the Request Class?
class EditPropertyRequest extends Request
{
/**
* Determine if the user owns this property and is authorized to make this request.
*
* #return bool
*/
public function authorize($id)
{
return Property::where('user_id', auth()->user()->id)
->where('id', $id)
->exists();
}
}
The error I get is
Missing argument 1 for
App\Http\Requests\EditPropertyRequest::authorize()
This is from doc
public function authorize()
{
$commentId = $this->route('comment');
return Comment::where('id', $commentId)
->where('user_id', Auth::id())->exists();
}
So $this->route('comment'); is a URL parameter Route::post('comment/{comment}');
request('id')
You can use request();

how to handle multiple urls pointing to same method in Laravel4 restful controller in one Route

I am trying out a restfull controller, but binding two urls this way does not seem to work anymore. How is this best handled?
// in the routes file
Route::get('/,new',array('as'=>'new_bit','uses'=>'BitsController#getNew'));
Route::controller('bits','BitsController');
// the controller
class BitsController extends BaseController {
public $restful = true;
/**
* Display a listing of the resource.
*
* #return Response
*/
public function getIndex()
{
return "this is the bits controller";
}
public function getNew()
{
return "this is the new page";
}
}
The solution for Laravel4 thanks to JasonLewis on Irc
Route::get('/{new?}', array('as' => 'new_bit', 'uses' => 'BitsController#getNew'))->where('new', 'new');

Categories