Undefined variable: $errors - laravel

i try show errors after validate a form.
i use this code on the view:
#if($errors->has())
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
#endif
and in the controller:
public function searchActivity(Request $request){
$this->validate($request, [
'search' => 'required',
'date' => 'required_with:search|required|date|after:yesterday'
]);
return view(App::getLocale() . '.activities.ActivityResults');
}
but dont work.
What could be happening?
note: i use Laravel 5.3.

The has method may be used to determine if any error messages exist
for a given field:
if ($errors->has('email')) {
//
}
So we can check like
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Ref Link : https://laravel.com/docs/5.3/validation

If you are getting the "Undefined variable: $errors...", check your routes and ensure that the route has the "web" middleware assigned to it. Check your route list:
php artisan route:list
As you can see from the sample output below, the admin routes do not have the "web" middleware assigned to it:
| | GET|HEAD | admin/home | home | App\Http\Controllers\HomeController#index | cors,auth
|
| | POST | admin/login | | App\Http\Controllers\Auth\LoginController#login | cors,guest
|
| | GET|HEAD | admin/login | login | App\Http\Controllers\Auth\LoginController#showLoginForm | cors,guest
|
| | POST | admin/logout | logout | App\Http\Controllers\Auth\LoginController#logout | cors
As mentioned by #patricus in his answer:
The $errors variable is made available to the views in the
Illuminate\View\Middleware\ShareErrorsFromSession middleware. This
middleware is included in the web middleware group by default.
If your route is not using the web middleware group, make sure that
whatever group it is in includes this middleware (along with
Illuminate\Session\Middleware\StartSession, since the errors are
stored in the session).
To fix this, wrap the affected routes in your routes/web.php or routes/api.php within a group and assign the "web" middleware to the group, like so:
Route::group(['middleware' => 'web'], function () {
Auth::routes();
});
Then check again:
php artisan route:list
Sample output:
| | POST | admin/login | | App\Http\Controllers\Auth\LoginController#login | cors,web,guest
|
| | GET|HEAD | admin/login | login | App\Http\Controllers\Auth\LoginController#showLoginForm | cors,web,guest
|
| | POST | admin/logout | logout | App\Http\Controllers\Auth\LoginController#logout | cors,web
|
| | POST | admin/password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController#sendResetLinkEmail | cors,web,guest
|
| | POST | admin/password/reset | password.update | App\Http\Controllers\Auth\ResetPasswordController#reset | cors,web,guest
|
| | GET|HEAD | admin/password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController#showLinkRequestForm | cors,web,guest
|
| | GET|HEAD | admin/password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController#showResetForm | cors,web,guest
|
| | POST | admin/register | | App\Http\Controllers\Auth\RegisterController#register | cors,web,guest
|
| | GET|HEAD | admin/register | register | App\Http\Controllers\Auth\RegisterController#showRegistrationForm | cors,web,guest

use #if($errors->any()) instead of #if($errors->has())
and if this could help this code works well with me
#if(!empty($errors))
#if($errors->any())
<ul class="alert alert-danger" style="list-style-type: none">
#foreach($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
</ul>
#endif
#endif

I think it is better use a front end validator like jqueryValidator.
Because to validate this form you have to turn off the Javascript in your browser.Then it will sometimes damage your work in loading datatables or related js works inside your project.
But if u are using a backend validation this may help you to understand it better.
Here, in the blade:
#if(!$errors->isEmpty())
<div class="alert alert-danger ">
×
<div class="error">
{{--#if(isset($errors))--}}
{{ $errors->first('email') }}
{{ $errors->first('password') }}
{{ $errors->first('confirmPassword') }}
{{ $errors->first('FirstName') }}
{{ $errors->first('LastName') }}
{{ $errors->first('JoinDate') }}
{{ $errors->first('dob') }}
</div>
</div>
#endif
And in the created request class inside the rule() function
return [
'email' => 'required|between:3,64|email|unique:employees',
'password' =>'required|min:5|max:10',
'confirmPassword' =>'required|same:password',
'FirstName' =>'required',
'JoinDate' =>'required|after:dob',
'LastName' =>'required',
'dob' =>'required',
];

#patricus made very good answer.
You can append 'web' middleware to your routes and all errors will appear in view:
Route::get('path', Controller::class .'#method')->middleware(['web']);

use
#foreach($errors as $error)
{{ $error}}}
#endforeach
I use this syntax for error

The $errors variable is made available to the views in the Illuminate\View\Middleware\ShareErrorsFromSession middleware. This middleware is included in the web middleware group by default.
If your route is not using the web middleware group, make sure that whatever group it is in includes this middleware (along with Illuminate\Session\Middleware\StartSession, since the errors are stored in the session).

Related

post to put/patch update on laravel

I got this html:
<form method="POST" action="http://localhost:8000/stories/13" accept-charset="UTF-8"><input name="_token" type="hidden" value="G9TVapBuoqmBxgnaqHKjfh9KEaYYE62Z7XEJdSUW">
<input name="_method" type="hidden" value="PATCH">
<h1>Modifica Storia</h1>
<div class="form-group">
<label for="titolo">Titolo</label>
<input class="form-control" name="titolo" type="text" value="Titolo" id="titolo">
</div>
<div class="form-group">
<label for="incipit">Incipit</label>
<textarea class="form-control" name="incipit" cols="50" rows="10" id="incipit">Incipt</textarea>
</div>
<input class="btn btn-primary" type="submit" value="Modifica">
</form>
generated by blade/laravel functions:
{{ Form::model($story, array('route' => array('stories.update', $story->idStories), 'method' => 'POST')) }}
<input name="_method" type="hidden" value="PATCH">
<h1>Modifica Storia</h1>
<div class="form-group">
{{ Form::label('titolo', 'Titolo') }}
{{ Form::text('titolo', old('titolo'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('incipit', 'Incipit') }}
{{ Form::textarea('incipit', old('incipit'), array('class' => 'form-control')) }}
</div>
{!! Form::submit('Modifica', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
I supposing to put the hidden field "_method" to let laravel form collective works on patch/put methods. I know that works only with GET/POST request.
This is the list of my routes:
/workspace/speechToTextStories$ php artisan route:list
+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+------------+
| | GET|HEAD | / | | App\Http\Controllers\HomeController#index | web,auth |
| | POST | broadcasting/auth | | Illuminate\Broadcasting\BroadcastController#authenticate | web |
| | POST | login | | App\Http\Controllers\Auth\LoginController#login | web,guest |
| | GET|HEAD | login | login | App\Http\Controllers\Auth\LoginController#showLoginForm | web,guest |
| | GET|HEAD | logout | | App\Http\Controllers\Auth\LoginController#logout | web |
| | POST | logout | logout | App\Http\Controllers\Auth\LoginController#logout | web |
| | POST | password/email | password.email | App\Http\Controllers\Auth\ForgotPasswordController#sendResetLinkEmail | web,guest |
| | GET|HEAD | password/reset | password.request | App\Http\Controllers\Auth\ForgotPasswordController#showLinkRequestForm | web,guest |
| | POST | password/reset | | App\Http\Controllers\Auth\ResetPasswordController#reset | web,guest |
| | GET|HEAD | password/reset/{token} | password.reset | App\Http\Controllers\Auth\ResetPasswordController#showResetForm | web,guest |
| | POST | register | | App\Http\Controllers\Auth\RegisterController#register | web,guest |
| | GET|HEAD | register | register | App\Http\Controllers\Auth\RegisterController#showRegistrationForm | web,guest |
| | GET|HEAD | stories | stories.index | App\Http\Controllers\StoriesController#index | web |
| | POST | stories | stories.store | App\Http\Controllers\StoriesController#store | web |
| | GET|HEAD | stories/create | stories.create | App\Http\Controllers\StoriesController#create | web |
| | GET|HEAD | stories/{story} | stories.show | App\Http\Controllers\StoriesController#show | web |
| | PUT|PATCH | stories/{story} | stories.update | App\Http\Controllers\StoriesController#update | web |
| | DELETE | stories/{story} | stories.destroy | App\Http\Controllers\StoriesController#destroy | web |
| | GET|HEAD | stories/{story}/edit | stories.edit | App\Http\Controllers\StoriesController#edit | web |
After hitting the submit buttons on the edit view im redirect to something like: url/stories/13
thats report the 404 errror. It seems that looking for the url in POST that doesnt exist!
Im confused where im wrong? Using resources on route is now deprecated? i build my own route names to make it works maybe?

Store method in Laravel Controller 5.5 on server does not work

I have developed a CRUD application in laravel 5.5
All methods works fine in local laravel (I mean with the "simulator" started by command php artisa serve), but after the deploy of the application in xampp the method store in my controller stop to works(just this)!
In my web.php I added this route:
Route::resource('example','exampleControllerView');
the result of the command php artisan:
POST | example | example.store | App\Http\Controllers\exampleControllerView#store
| | GET|HEAD | example | example.index | App\Http\Controllers\exampleControllerView#index
| | GET|HEAD | example/create | example.create | App\Http\Controllers\exampleControllerView#create
| | GET|HEAD | example/{example} | example.show | App\Http\Controllers\exampleControllerView#show
| | PUT|PATCH | example/{example} | example.update | App\Http\Controllers\exampleControllerView#update
| | DELETE | example/{example} | example.destroy | App\Http\Controllers\exampleControllerView#destroy
| | GET|HEAD | example/{example}/edit | example.edit | App\Http\Controllers\exampleControllerView#edit
this is the method store in my controller
public function store(Request $request)
{
$request->validate([
'name' => 'required|min:4',
'description'=> 'required',
]);
$example = example::create(['name' => $request->name,'description' => $request->description]);
return redirect('/example/'.$example->id);
}
This is the view create (url : http://localhost/project/public/example/create):
<form action="/example" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">example nome</label>
<input type="text" class="form-control" id="taskTitle" name="name">
</div>
<div class="form-group">
<label for="description">example descrizione</label>
<input type="text" class="form-control" id="exampleDescription" name="description">
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<button type="submit" class="btn btn-primary">Submit</button>
After the submit button I see in the new page this uri:
http://localhost/example
and in the page a 404 error: Object not found!
The requested URL does not exist on this server.
I thing that is a problem of routing and url but I don not the why in local all work fine...
thanks in advances
Change this line-
<form action="/example" method="post">
To this-
<form action="/project/public/example" method="post">
Better use Laravel Collective, this will automatically configure your base path and has a lot of other benefits like csrf protection.
Your code should work fine. It redirects a user to the show method with ID of created entity. Instead of using model binding, try to do this:
public function show($id)
{
dd('The show method was executed and ID is ' . $id);
....
}

Admin LTE in Laravel 5.3.* URL/Routes

|--------------------------------------------------------------------------
| URLs
|--------------------------------------------------------------------------
|
| Register here your dashboard, logout, login and register URLs. The
| logout URL automatically sends a POST request in Laravel 5.3 or higher.
| You can set the request to a GET or POST with logout_method.
| Set register_url to null if you don't want a register link.
|
*/
'dashboard_url' => 'home',
'logout_url' => 'logout',
'logout_method' => null,
'login_url' => 'login',
'register_url' => 'register',
please help me with my problem, i am a newbie in terms of programming i need help regarding to the URL/Routes of the admin LTE, i cannot find the routes admin LTE using, and can anyone explain what is the uses of each parameters above thanks.
I'll speak quickly and briefly:
'dashboard_url' => 'home'
dashboard_url: Here will be your main application page, will set the first page. Based on your configuration URLs, from this depends on which technology you are using to define these routes. I myself use Laravel, so I need to define my routes in routes/web.php.
'logout_url' => 'logout'
logout_url: Where you will be directed after you leave
'login_url' => 'login'
login_url: Your login page
'register_url' => 'register'
register_url: | You can set the request to GET or POST with logout_method.
| Set register_url to null if you do not want to register link. (I have not used this yet, sorry)
Example:
Here you define your routes and when using in laravel then will call according to the configurations of AdminLTE
My route
$this->group(['middleware' => ['auth'], 'namespace' => 'Admin'], function(){
$this->get('/', 'AdminController#index')->name('admin.home');
});
My index
(My logout)
<li class="user-footer">
<div class="float-left">
Perfil
</div>
<div class="float-right">
<a href="#" class="btn btn-default btn-flat"
onclick="event.preventDefault(); document.getElementById('logout-form').submit();" >
{{ trans('adminlte::adminlte.log_out') }}
</a>
<form id="logout-form" action="{{ url(config('adminlte.logout_url', 'auth/logout')) }}" method="POST" style="display: none;">
#if(config('adminlte.logout_method'))
{{ method_field(config('adminlte.logout_method')) }}
#endif
{{ csrf_field() }}
</form>
</div>
</li>

Laravel: update method in controller not working

My Form in the edit view:
<form class="form-horizontal" role="form" method="PUT" action="{{ route('locations.update', $location->id) }}">
{{ csrf_field() }}
// All form Fields ...
</form>
My routs for this case:
| GET|HEAD | locations/create | locations.create | App\Http\Controllers\LocationController#create
| PUT|PATCH | locations/{location} | locations.update | App\Http\Controllers\LocationController#update
| GET|HEAD | locations/{location} | locations.show | App\Http\Controllers\LocationController#show
| DELETE | locations/{location} | locations.destroy | App\Http\Controllers\LocationController#destroy
My update method in the locations controller
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
dd($request);
}
The result on form submitting
the dd($request); result is not showing up.
Any hints for me what i am doing wrong here?
Thanks a lot!
Web browsers don't support PUT routes, only GET and POST. To solve this, you can use Form Method Spoofing By adding a hidden field to your form. Like so:
<form class="form-horizontal" role="form" method="post" action="{{ route('locations.update', $location->id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT">
// All form Fields ...
</form>

Form::open get the wrong route if the page is called by Redirect::back

On my route.php I have
Route::resource('users', 'UserController');
Artisan route command gives me
+--------+-----------------------------+---------------+------------------------+----------------+---------------+
| Domain | URI | Name | Action | Before Filters | After Filters |
+--------+-----------------------------+---------------+------------------------+----------------+---------------+
| | GET|HEAD / | | Closure | | |
| | GET|HEAD users | users.index | UserController#index | | |
| | GET|HEAD users/create | users.create | UserController#create | | |
| | POST users | users.store | UserController#store | | |
| | GET|HEAD users/{users} | users.show | UserController#show | | |
| | GET|HEAD users/{users}/edit | users.edit | UserController#edit | | |
| | PUT users/{users} | users.update | UserController#update | | |
| | PATCH users/{users} | | UserController#update | | |
| | DELETE users/{users} | users.destroy | UserController#destroy | | |
+--------+-----------------------------+---------------+------------------------+----------------+---------------+
Then I have a page for editing users with 2 forms, the first one for editing, the second one for deleting:
{{ Form::open(array('route' => array('users.update', $user->id), 'method' => 'put')) }}
...
{{ Form::open(array('route' => array('users.destroy', $user->id), 'method' => 'delete')) }}
Finally into the UserController I use a validation that redirect to the previous page in case of unsuccesful validation:
if (!$this->user->isValid($id))
{
return Redirect::back()->withInput()->withErrors($this->user->errors);
}
When I land on the edit page from the the users list page, the HTML for both forms looks fine (note the hidden _method field with value DELETE):
<form method="POST" action="http://www.virtualbox.me/users/8" accept-charset="UTF-8"><input name="_method" type="hidden" value="PUT">
...
<form method="POST" action="http://www.virtualbox.me/users/8" accept-charset="UTF-8"><input name="_method" type="hidden" value="DELETE">
But if I insert a value on a field that cause the validation to fail, then on the reloaded page also the second form get method PUT instead of DELETE:
<form method="POST" action="http://www.virtualbox.me/users/8" accept-charset="UTF-8"><input name="_method" type="hidden" value="PUT">
...
<form method="POST" action="http://www.virtualbox.me/users/8" accept-charset="UTF-8"><input name="_method" type="hidden" value="PUT">
Am I doing something wrong?
Something like this might work.... change this line to:
return Redirect::back()->withInput(Input::except('_method'))->withErrors($this->user->errors);
Actually Laravel automatically change your method behind the scene it is mentioned as a note in Docs. As browsers don't understand PUT, PATCH, DELETE requests.
So you need to add the _method field explicitly in your DELETE form.
<field type="hidden" name="_method" value="DELETE">

Resources