laravel's validator doesnt return input fields - laravel

problems with returning inputs. after form submitted, if validator fails it doesnt return 'old' inputs. here's my controller
$validator = Validator::make($request->all(), [
'user_rate' => 'required|integer|between:1,5',
'user_comment' => 'required',
], [
"user_rate.integer" => trans('errors.rate-required'),
"user_rate.between" => trans('errors.rate-required'),
"user_rate.required" => trans('errors.rate-required'),
"user_comment.required" => trans('errors.com-required'),
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->input());
//return redirect()->back()->with(Input::all());
}
i have tried several ways(also $request->flash(), but it doesnt return 'old' inputs

In your controller
public function someFunction(Request $request)
{
//Validation Logic
if($v->fails())
{
return redirect()->back()->withInput();
}
}
In your view
<input type="text" name="some_name" value="{{old('some_name')}}">
Hope this helps.

Don't pass any arguments to the withInput function
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
//return redirect()->back()->with(Input::all());
}
and how are you getting the old inputs in your form?

Related

Return to view from another function in laravel

Hi I'm saving information from blade. The form goes to store function. After saving data I have to send push info using GCM. But this function can not return to view. How can solve this?
public function store(Request $request)
{
$request->validate([
'title_uz' => 'required',
'desc_uz' => 'required',
'url_uz' => 'required',
'company_id' => 'required',
]);
News::create($request->all());
$this->versionUpdate();
$this->sendpush($request);
}
And next function
public function sendpush (Request $request)
{
$fcmUrl = 'https://fcm.googleapis.com/fcm/send';
$notification = [
'title' => $request->title_uz,
'text' => $request->desc_uz,
];
***** here is some functions *******
$result = curl_exec($ch);
curl_close($ch);
$result_to = json_decode($result);
if ($result_to === null) {
return redirect()->route('news.index')
->with('success','DIQQAT!!! Yangilik qo`shildi ammo push-xabar yuborilmadidi.');
}
else {
return redirect()->route('news.index')
->with('success','Yangilik qo`shildi va push-xabar muvoffaqiyatli yuborildi.');
}
}
$result_to returns value but the browser holds at blank screen. It seems the store function holds at the end.
Try this line return $this->sendpush($request);instead of this $this->sendpush($request);
you have redirect from this method so you can try like these
$result_to = $this->sendpush($request);;
if ($result_to === null) {
return redirect()->route('news.index')
->with('success','DIQQAT!!! Yangilik qo`shildi ammo push-xabar yuborilmadidi.');
}
else {
return redirect()->route('news.index')
->with('success','Yangilik qo`shildi va push-xabar muvoffaqiyatli yuborildi.');
}

an added value of array of request disappears in Laravel Controller

the user id is existed Before doing create. so it causes an error in the first one.
I made it the other way. the second one below works correctly.
I would like to know why the first one is wrong and it's gone.
//Error
public function store(ContactRequest $request)
{
$request->user_id = $request->user()->id;
Log::debug($request->user()->id);
Log::debug($request);
Contact::create($request->all());
}
//OK
public function store(ContactRequest $request,Contact $contact)
{
$request->user_id = $request->user()->id;
$contact->title = $request->title;
$contact->body = $request->body;
$contact->user_id = $request->user()->id;
$contact->save();
}
the log of the first one is here.
What happened to the user_id!?
[2020-05-30 15:59:10] local.DEBUG: 59
[2020-05-30 15:59:10] local.DEBUG: array (
'_token' => 'gGWuxW6C2JRSCYDuCAC9HauynGclKQEQB7qUh6Rw',
'title' => 'TITLE',
'body' => 'MESSAGE',
'action' => 'SEND',
)
Contact is model class.
ContactRequest is here.
class ContactRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|max:100',
'body' => 'required|max:1000'
];
}
public function attributes() {
return [
'title' => 'title',
'body' => 'CONTENTS'
];
}
}
You will have to use $request->merge(['user_id'=>$request->user()->id]).
Another tips is that you can simply use Auth::user()->id which also return the user id of current user.
What if you do this:
Auth::user() - >contact($request->all()) - >save() ;
Or also as an experiment:
$contact = new Contact($request->all()) ;
$contact->user_id = Auth::user() - >id;
$contact->save() ;
Actually the second snippet will surely work. The first one I did not test though it looks nice. :)

Find data before validate form request laravel

I want to update the data using the request form validation with a unique email role, everything works normally.
Assume I have 3 data from id 1-3 with url:
127.0.0.1:8000/api/user/update/3
Controller:
use App\Http\Requests\Simak\User\Update;
...
public function update(Update $request, $id)
{
try {
// UPDATE DATA
return resp(200, trans('general.message.200'), true);
} catch (\Exception $e) {
// Ambil error
return $e;
}
}
FormRequest "Update":
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->id,
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
but if the updated id is not found eg:
127.0.0.1:8000/api/user/update/4
The response gets The email has already been taken.
What is the solution so that the return of the data is not found instead of validation first?
The code looks like it should work fine, sharing a few things below that may help.
Solution 1: Check if $this->id contains the id you are updating for.
Solution 2: Try using the following changes, try to get the id from the URL segment.
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->segment(4),
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
Sharing one more thing that may help you.
Some person uses Request keyword at the end of the request name. The Update sounds generic and the same as the method name you are using the request for. You can use UpdateRequest for more code readability.
What I understand from your question is, you need a way to check if the record really exists or not in the form request. If that's the case create a custom rule that will check if the record exists or not and use that rule inside your request.
CheckRecordRule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CheckRecordRule implements Rule
{
protected $recordId;
public function __construct($id)
{
$this->recordId = $id;
}
public function passes($attribute, $value)
{
// this will check and return true/false
return User::where('id', $this->recordId)->exists();
}
public function message()
{
return 'Record not found.';
}
}
Update form request
public function rules()
{
return [
'email' => 'required|email|unique:users,email,' . $this->id.'|'. new CheckRecordRule($this->id),
];
}
So when checking for duplicate it will also check if the record really exists or not and then redirect back with the proper message.

Laravel 5, can't insert via request method doesn't exist

That's what i'm trying to do without any success:
In welcome.blade I have a foreach with some boards and subboards(random generated by user) where you can click on subboard and go something like this /subboardOne. I got this on my routes.php
Route::get('/{subboaName}', 'ThreadController#index');
Route::post('/{subboaName}', 'ThreadController#store');
then you can post a thread on this subboard via form but since i really don't know how laravel knows where he is, the form is something like this:
<form class="form col-md-12 center-block" role="form" method="POST" action="/{{$subboardcoll->id}}">
this $subboardcoll->id comes from the controller, where it sends via the index function the collection:
public function index($subboard)
{
$subboardcoll = Subboard::where('subboaName', $subboard)->first();
$threads = Thread::where('subboaId', $subboardcoll->id)
->orderBy('created_at', 'desc')
->get();
return view('threads.thread', compact('threads', 'subboardcoll'));
}
then i'm trying to send my form and store the thread autoinserting the subboardId but laravel doesn't recognize subboards method:
public function store(Request $request)
{
$this->validate($request, [
'comentario' => 'required|max:2000',
//'g-recaptcha-response' => 'required|recaptcha',
//'imagen' => 'required',
]);
$request->subboards()->threads()->create([
'thrName' => $request->nombre,
'thrComment' => $request->comentario,
'thrImg' => $request->imagen,
'thrSubject' => $request->tema,
]);
return redirect()->back();
}
And gives me this erorr:
BadMethodCallException in Macroable.php line 81: Method subboards does not exist.
Can you guys helpme to know why? also is there better form to do what i'm trying? im newbie on laravel, thanks
EDIT:
Thread.php
public function subboard()
{
return $this->belongsTo(Subboard::class, 'subboaId');
}
Subboard.php
public function thread()
{
return $this->hasMany(Thread::class);
}
The method subboards do not exist in a request object. Consider doing this
public function store($id, Request $request)
{
$this->validate($request, [
'comentario' => 'required|max:2000',
//'g-recaptcha-response' => 'required|recaptcha',
//'imagen' => 'required',
]);
Subboard::find($id)->threads()->create([
'thrName' => $request->nombre,
'thrComment' => $request->comentario,
'thrImg' => $request->imagen,
'thrSubject' => $request->tema,
]);
//Alternative query statement
Subboard::where('id', $id)->first()->threads()->create([.....
return redirect()->back();
}

Better way for testing validation errors

I'm testing a form where user must introduce some text between let's say 100 and 500 characters.
I use to emulate the user input:
$this->actingAs($user)
->visit('myweb/create')
->type($this->faker->text(1000),'description')
->press('Save')
->see('greater than');
Here I'm looking for the greater than piece of text in the response... It depends on the translation specified for that validation error.
How could do the same test without having to depend on the text of the validation error and do it depending only on the error itself?
Controller:
public function store(Request $request)
{
$success = doStuff($request);
if ($success){
Flash::success('Created');
} else {
Flash::error('Fail');
}
return Redirect::back():
}
dd(Session::all()):
`array:3 [
"_token" => "ONoTlU2w7Ii2Npbr27dH5WSXolw6qpQncavQn72e"
"_sf2_meta" => array:3 [
"u" => 1453141086
"c" => 1453141086
"l" => "0"
]
"flash" => array:2 [
"old" => []
"new" => []
]
]
you can do it like so -
$this->assertSessionHas('flash_notification.level', 'danger'); if you are looking for a particular error or success key.
or use
$this->assertSessionHasErrors();
I think there is more clear way to get an exact error message from session.
/** #var ViewErrorBag $errors */
$errors = request()->session()->get('errors');
/** #var array $messages */
$messages = $errors->getBag('default')->getMessages();
$emailErrorMessage = array_shift($messages['email']);
$this->assertEquals('Already in use', $emailErrorMessage);
Pre-requirements: code was tested on Laravel Framework 5.5.14
get the MessageBag object from from session erros and get all the validation error names using $errors->get('name')
$errors = session('errors');
$this->assertSessionHasErrors();
$this->assertEquals($errors->get('name')[0],"The title field is required.");
This works for Laravel 5 +
Your test doesn't have a post call. Here is an example using Jeffery Way's flash package
Controller:
public function store(Request $request, Post $post)
{
$post->fill($request->all());
$post->user_id = $request->user()->id;
$created = false;
try {
$created = $post->save();
} catch (ValidationException $e) {
flash()->error($e->getErrors()->all());
}
if ($created) {
flash()->success('New post has been created.');
}
return back();
}
Test:
public function testStoreSuccess()
{
$data = [
'title' => 'A dog is fit',
'status' => 'active',
'excerpt' => 'Farm dog',
'content' => 'blah blah blah',
];
$this->call('POST', 'post', $data);
$this->assertTrue(Post::where($data)->exists());
$this->assertResponseStatus(302);
$this->assertSessionHas('flash_notification.level', 'success');
$this->assertSessionHas('flash_notification.message', 'New post has been created.');
}
try to split your tests into units, say if you testing a controller function
you may catch valication exception, like so:
} catch (ValidationException $ex) {
if it was generated manually, this is how it should be generated:
throw ValidationException::withMessages([
'abc' => ['my message'],
])->status(400);
you can assert it liks so
$this->assertSame('my message', $ex->errors()['abc'][0]);
if you cannot catch it, but prefer testing routs like so:
$response = $this->json('POST', route('user-post'), [
'name' => $faker->name,
'email' => $faker->email,
]);
then you use $response to assert that the validation has happened, like so
$this->assertSame($response->errors->{'name'}[0], 'The name field is required.');
PS
in the example I used
$faker = \Faker\Factory::create();
ValidationException is used liks this
use Illuminate\Validation\ValidationException;
just remind you that you don't have to generate exceptions manually, use validate method for common cases:
$request->validate(['name' => [
'required',
],
]);
my current laravel version is 5.7

Resources