Laravel error is not passed to view - laravel

I can't figure put why laravel blade doesn't catch my error validation and doesn't pass it to my view.
In detail
I do have error snippet in my blade template
below is my validation which works correctly
What I'm missing?
Thank you
This is json message I see instead of message in blade template
{
message: "The given data was invalid.",
status_code: 500
}
This snippet I use to let user know about error
#if(count($errors))
<div class="form-group">
<div class="alert alert-danger">
<ul>
#if($errors->all())
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
#endif
</ul>
</div>
</div> #endif
And finally this is my correctly working validation
$request->validate([
'email' => 'required|email|unique:subscribers|max:255',
]);
EDIT:
This is the rout in web.php
Route::post('saveemail', 'SaveSubscriberEmailController#saveEmail');
And this is the method
namespace App\Http\Controllers;
use App\subscriber;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;
class SaveSubscriberEmailController extends Controller
{
public function saveEmail(Request $request)
{
$request->validate([
'email' => 'required|email|unique:subscribers|max:255',
]);
$uuid = Uuid::uuid4();
$subscriber = new subscriber();
$subscriber->email = $request->email;
$subscriber->uuid = $uuid->toString();
$subscriber->created_at = Carbon::now();
$subscriber->save();
flash('Registration conformation email has been sent. Please check your mailbox. Thank you!')->success();
return redirect()->back();
}
}

I've had this problem before and the way I was able to fix it was to wrap the routes with a middleware group that includes the middleware \Illuminate\View\Middleware\ShareErrorsFromSession::class. It adds the session's errors to the view.
In your Kernel.php class's protected $middlewareGroups array it can look something like:
'web' => [
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
// other middleware
],
Then where you declare your routes you can do:
Route::group(['middleware' => ['web']], function () {
Route::post('saveemail', 'SaveSubscriberEmailController#saveEmail');
};

Request validation only send error of 422 not 500 if you are getting this error it's because of something else and the formRequest error bag won't catch this error .

Route::post('saveemail', 'SaveSubscriberEmailController#saveEmail');
Put this route into web middleware. you can do this like
Route::middleware(['web'])->group(function () {
Route::post('saveemail', 'SaveSubscriberEmailController#saveEmail');
});
Change your controller to this.
class SaveSubscriberEmailController extends Controller
{
public function saveEmail(Request $request)
{
$validator = validate($request->all(),[
'email' => 'required|email|unique:subscribers|max:255',
]);
if($validator->fails()){
return back()->withErrors($validator);
}
$uuid = Uuid::uuid4();
$subscriber = new subscriber();
$subscriber->email = $request->email;
$subscriber->uuid = $uuid->toString();
$subscriber->created_at = Carbon::now();
$subscriber->save();
flash('Registration conformation email has been sent. Please check your mailbox. Thank you!')->success();
return redirect()->back();
}
}
Hope this helps

Related

Laravel 5.5 - save(); wont save to the database and does not output an error

I am trying to make an registration form with laravel 5.5 and mysql but the problem is it wont submit to the database..
PageController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PageController extends Controller
{
public function main(){
if (!Auth::Check()) {
return view('auth.login');
}
return view('user.main');
}
public function register_check(Request $request){
$this->validate($request, [
'username' => 'required|min:2|max:12|unique:users',
'fname' => 'required|min:5|max:20',
'position' => 'required|not_in:0',
'password' => 'required|min:6|max:12',
'ConfirmPass' => 'required|same:password',
'contactnum' => 'required|min:2|max:12'
]);
$user = new User;
$user->username = $request['username'];
$user->fname = $request['fname'];
$user->position= $request['position'];
$user->password = bcrypt($request['password']);
$user->ConfirmPass = $request['ConfirmPass'];
$user->contactnum = $request['contactnum'];
$user->save();
}
}
route web.php
Route::get('/', [
'as'=>'index',
'uses'=> 'PageController#main'
]);
Route::get('/register', [
'as'=>'register',
'uses'=> 'PageController#register'
]);
Route::post('/register_check', [
'as'=>'register_check',
'uses'=>'PageController#register_check'
]);
Any help will be greatly appreciated. thank you in advance
I am guessing there is an error in validation and you are being redirected back to the form. You might not be checking for $errors in your form view hence you don't see what the error is.
Place this code in your form view file. To see if there are any validation errors.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
The best way to deal with such situation is to check the response of save() function like:
if( $user->save() )
{
// Success message here
}
else
{
// Failure message here
}
now you will gt to know whether the save is successful or not.

Laravel Editing post doesn't work

There are routes
Route::get('posts', 'PostsController#index');
Route::get('posts/create', 'PostsController#create');
Route::get('posts/{id}', 'PostsController#show')->name('posts.show');
Route::get('get-random-post', 'PostsController#getRandomPost');
Route::post('posts', 'PostsController#store');
Route::post('publish', 'PostsController#publish');
Route::post('unpublish', 'PostsController#unpublish');
Route::post('delete', 'PostsController#delete');
Route::post('restore', 'PostsController#restore');
Route::post('change-rating', 'PostsController#changeRating');
Route::get('dashboard/posts/{id}/edit', 'PostsController#edit');
Route::put('dashboard/posts/{id}', 'PostsController#update');
Route::get('dashboard', 'DashboardController#index');
Route::get('dashboard/posts/{id}', 'DashboardController#show')->name('dashboard.show');
Route::get('dashboard/published', 'DashboardController#published');
Route::get('dashboard/deleted', 'DashboardController#deleted');
methods in PostsController
public function edit($id)
{
$post = Post::findOrFail($id);
return view('dashboard.edit', compact('post'));
}
public function update($id, PostRequest $request)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return redirect()->route('dashboard.show', ["id" => $post->id]);
}
but when I change post and click submit button, I get an error
MethodNotAllowedHttpException in RouteCollection.php line 233:
What's wrong? How to fix it?
upd
opening of the form from the view
{!! Form::model($post, ['method'=> 'PATCH', 'action' => ['PostsController#update', $post->id], 'id' => 'edit-post']) !!}
and as result I get
<form method="POST" action="http://mytestsite/dashboard/posts?6" accept-charset="UTF-8" id="edit-post"><input name="_method" type="hidden" value="PATCH"><input name="_token" type="hidden" value="aiDh4YNQfLwB20KknKb0R9LpDFNmArhka0X3kIrb">
but why this action http://mytestsite/dashboard/posts?6 ???
Try to use patch instead of put in your route for updating.
Just a small tip you can save energy and a bit of time by declaring the Model in your parameters like this:
public function update(Post $id, PostRequest $request)
and get rid of this
$post = Post::findOrFail($id);
EDIT
You can use url in your form instead of action :
'url'=> '/mytestsite/dashboard/posts/{{$post->id}}'
Based on the error message, the most probable reason is the mismatch between action and route. Maybe route requires POST method, but the action is GET. Check it.
Try to send post id in hidden input, don't use smt like that 'action' => ['PostsController#update', $post->id]
It contribute to result action url.

How do i separate two error message in laravel using one error blade file?

Say,i have two form in one page.I have included one error blade file bellow both of the form. Now when i make wrong in one form & submit it the error message is showing bellow the both form.Its normal.But my question is, how do i separate this two error message,how can i differentiate by giving them two different name?
Give this a try
return redirect()->back()->withErrors([
'form1.name' => 'name is required in Form 1',
'form1.email' => 'email is required in Form 1',
'form2.city' => 'city is required in form 2'
]);
in your view
#if($errors->any())
#foreach ($errors->get('form1.*') as $error) {
{{ $error }}
#endforeach
#endif
So you can group errors by form using array notation form.name and get all with $errors->get('form.*).
Read more about errors here: https://laravel.com/docs/5.4/validation#working-with-error-messages
If you're using Form Request Validation, you can change the errorBag property to get a unique array of errors for your view file.
In your Request file:
class MyFormRequest {
protected $errorBag = 'foobar';
public function rules() { // ... }
}
In your controller:
public function store(MyFormRequest $request) {
// Store entry.
}
Then in your view file:
#if ($errors->foobar->isNotEmpty())
// Work with the errors
#endif
You can use the named error bags.
$validator = Validator::make($request->all(), [
'field1' => 'required',
'field2' => 'required|digits:1',
]);
if ($validator->fails()) {
return back()
->withErrors($validator, 'form1error')
->withInput();
}
To print the error in blade file use-
#if(count($errors->form1error)>0)
<ul>
#foreach($errors->form1error->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif

Laravel 5.2 Custom validation message with custom validation function

I want to create custom validation rule with custom validation error message. For this I created a rule:
$rule => [
'app_id' => 'isValidTag'
]
And for custom message:
$message => [
app_id.isValidTag => 'Not a Valid id'
];
After that I created Service Provider:
class CustomValidationServiceProvider extends ServiceProvider
{
public function boot() {
//parent::boot();
$this->app->validator->resolver(function($transator,$data,$rules,$messages){
return new CustomValidator($transator,$data,$rules,$messages);
});
}
}
And my Custom validation class is:
class CustomValidator extends Validator {
if(empty($parameters)) {
return true;
}
$conext = $parameters[0];
$tag = Tag::where('id', $value)->where('context', $conext)->get();
$flag = false;
if($tag->count() > 0) {
$flag = true;
}
return $flag;
}
All is working fine but the issue is my custom message for app_id.isValidTag is not working even all other message are working fine.
Please suggest me what I missing here or in Laravel 5.2 there is some change to display message. Any idea will be appreciated.
Here is a great tutorial for this: http://itsolutionstuff.com/post/laravel-5-create-custom-validation-rule-exampleexample.html
I think you did it Laravel 4.* way. This is how it is done in Laravel 5.2
in my example where i was making registration authorisation form so files like AuthController.php was premade:
AuthController.php
Validator::make($data, [
...
// add your field for validation
'name_of_the_field' => 'validation_tag', // validation tag from validation.php
...
CustomAuthProvider.php
// if you didn't make a custom provider use Providers/AppServiceProvider.php
public function boot() {
...
Validator::extend('validation_tag', function($attribute, $value, $parameters, $validator) {
// handle here your validation
if ( your_query ) {
return true;
}
return false;
});
validation.php
...
// add your validation tag and message to be displayed
'validation_tag' => 'The field :attribute isn't good',
...
file.blade.php
// to add at the end of the page all your errors add
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

How to get a custom message on fail login credentials in Laravel?

I use this code to check user credentials, but I can't figure how to change the code to get an error message when credentials fail. Used redirect and so on, but show nothing....
public function loginWithCredentials(Request $request) {
$signinEmail = $request->input('email');
$signinPassword = $request->input('password');
$user = new Users();
$errors = new MessageBag;
$user = $user
->where('email', '=', $signinEmail)
->get()->first();
if(empty($user)) {
$errors->add('error', 'Invalid credentials!');
return json_encode([
'error'=>true,
'messages'=>$errors
]);
}
$userdata = $user->toArray();
if(md5($signinPassword) != $userdata['password']) {
$errors->add('error', 'Invalid credentials!');
return redirect()->guest('auth/login');
}
Session::put('user',$userdata);
$errors->add('message0', 'Welcome ' . strtoupper($userdata['username']) . '!');
}
Now it just simple redirects me to a white page with the "invalid credentials" message. I want the message to be on login page.
Your code you has some flaws, consider fixing it.
Why are you mixing json response with html response?
Consider using bcrypt() for hashing your users passwords instead md5().
Add some sort of validation, Laravel has the built in validation.
Laravel ships with easy use login auth, take a look at.
So in your code needs some changes here it is:
public function loginWithCredentials(Request $request) {
$signinEmail = $request->input('email');
$signinPassword = $request->input('password');
$user = new Users();
$user = $user
->where('email', '=', $signinEmail)
->get()->first();
if(empty($user) || md5($signinPassword) != $user->password) {
return redirect()->back()->with('message', 'Invalid credentials!');
}
$userdata = $user->toArray();
Session::put('user', $userdata);
return view('view.name')->with('message', 'Welcome ' . strtoupper($userdata['username']) . '!');
}
Then in your view you write the success message like so:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
this example is using blade, but should be similar to other views.
You just need to override AuthenticatesUsers Trait method named sendFailedLoginResponse like this:
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Request;
class LoginController extends Controller
{
use AuthenticatesUsers;
...
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
'your array key' => ['Place your custom message here'],
]);
}
...
}
That's It!
I hope this will help you. :)

Resources