I'm trying to do flash messages in Laravel, now the flash messages work for success messages and error messages on pages that don't have checkboxes.
I have a view called 'deleteappointmentform' which requires the user to check a checkbox and it deletes the checked appointments, however if I don't check any checkbox and click submit it gives me a success message without actually checking if they've checked and checkboxes. I'm trying to get it to display an error message if they don't check any checkboxes
Any help's appreciated, thanks
This is the function that deals with deleting appointments
function deleteAppointment(Request $request)
{
Appointment::destroy($request->appointments);
Session::flash('successCancelAppointment', 'Appointment cancelled successfully!');
return redirect('all');
}
This is my messages blade
#if (Session::has('successCancelAppointment'))
<div class="alert alert-success" role="alert">
<strong>Success: </strong> {{Session::get('successCancelAppointment')}}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger" role="alert">
<strong>Errors:</strong>
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
This is my deleteappointmentsblade
#extends('layouts.master')
#section('title', 'Cancel Appointment')
#section('content')
<form action="{{url('deleteappointment')}}" method="POST">
{{ csrf_field() }}
#foreach ($appointments as $appointment)
<div>
<label> {{$appointment->user->firstname}} {{$appointment->user->surname}}</label>
<label>Has an appointment at: {{$appointment->time}}</label>
<label>On: {{$appointment->date}}</label>
<label>With Dr: {{$appointment->doctor->surname}}</label>
<input type='checkbox' value='{{$appointment->id}}' name='appointments[]'/>
</div>
#endforeach
<input type="submit" name="submitBtn" value="Cancel Appointments">
</form>
#endsection
you can try this
function deleteAppointment(Request $request)
{ $rules=array(
'appointments'=>'required'
);
$validator = Validator::make($request->all(), $rules);
if($validator->fails())
{
$messages = $validator->messages();
$errors = $messages->all();
return redirect()->back()->withErrors($errors);
}
Appointment::destroy($request->appointments);
Session::flash('successCancelAppointment', 'Appointment cancelled
successfully!');
return redirect('all');
}
Related
what happen to my update file?
I can't update file in my program, what's wrong with my controller?
edit.blade.php
<div class="row">
<div class="col-12">
{{ Form::model($activityreports,['route'=>['activityreports.update',$activityreports['id']], 'files'=>true, 'method'=>'GET', 'enctype'=>'multipart/form-data']) }}
<div class="card">
<div class="card-body">
#if(!empty($errors->all()))
<div class="alert alert-danger">
{{ Html::ul($errors->all())}}
</div>
#endif
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ Form::label('file', 'Laporan Kegiatan') }}
{{ Form::file('file', ['class'=>'form-control']) }}
</div>
</div>
</div>
</div>
</div>
<!-- </form> -->
{{ Form::close() }}
</div>
</div>
controller
public function update(Request $request, $id)
{
//
$rules=[
'title'=>'required',
'date'=>'required',
'type'=>'required',
'place'=>'required'
];
$pesan=[
'title.required'=>'Judul Kegiatan Tidak Boleh Kosong',
'date.required'=>'Tanggal Kegiatan Tidak Boleh Kosong',
'type.required'=>'Jenis Kegiatan Tidak Boleh Kosong',
'place.required'=>'Lokasi Kegiatan Tidak Boleh Kosong',
];
$validator=Validator::make(Input::all(),$rules,$pesan);
if ($validator->fails()) {
return Redirect::to('admin/activityreports/'.$id.'/edit')
->withErrors($validator);
}else{
$fileName="";
$activityreports=Activityreports::find($id);
if($request->hasFile('file')){
Storage::delete($activityreports->file);
$file=$request->file('file');
$fileName=$file->getClientOriginalName();
$file->move('storage/file/activityreportsFile/', $fileName);
$activityreports->file=$fileName;
}
$activityreports->title=Input::get('title');
$activityreports->date=Input::get('date');
$activityreports->type=Input::get('type');
$activityreports->place=Input::get('place');
$activityreports->save();
Session::flash('message','Data Berhasil Diubah');
return Redirect::to('admin/activityreports/index');
}
I tried another code and there is error 'Call to member function getClientOriginalName on null. And when I make file required then input file, there is always warning to input .pdf file.
First, wehre is the problem which causes the error:
This line $file=$request->file('file'); sets $fileto null, therefore you cannot call the function in the next line.
This means that no file is present in your request. You can check your request if you call dd($request->all()) in your update method.
Second, why does this happen?
I think your problem is that you create a GET form in your view and therefore a GET request will be sent. You will probably have to make a POST request (you could also make a PATCH request since you call the update method in your controller).
Please change the form to POST and your route to POST and try it again.
With laravel 7 /livewire 1.3 app in login form I got errors on invalid form with code:
public function submit()
{
$loginRules= User::getUserValidationRulesArray();
$this->validate($loginRules);
and shows error message near with any field
I want on login fail to add flash message and reading at
https://laravel.com/docs/7.x/validation
I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect()->to('/login');
}
I got flash message, but validation errors for any field is lost.
If I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect('/login')
->withErrors($validator)
->withInput();
}
and I got error :
Method Livewire\Redirector::withErrors does not exist.
in routes/web.php I have :
Route::livewire('/login', 'login')->name('login');
MODIFIED :
In component app/Http/Livewire/Login.php :
<?php
namespace App\Http\Livewire;
use App\User;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Auth;
use DB;
use App\Config;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class Login extends Component
{
public $form= [
'email'=>'admin#mail.com',
'password'=> '111111',
];
private $view_name= 'livewire.auth.login';
public function submit()
{
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return;
// return redirect()->to('/login');
}
$user = Sentinel::findByCredentials(['email' => $this->form['email']]);
if (empty($user)) {
session()->flash('danger_message', 'User "' . $this->form['email'] . '" not found !');
...
and template resources/views/livewire/auth/login.blade.php :
<article >
#include('livewire.common.alert_messages')
<form class="form-login" wire:submit.prevent="submit">
<div class="card">
#if ($errors->any())
Check your login credentials
#endif
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<div class="card-body card-block">
<h3 class="card-header">
<span class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</span>
Login
</h3>
<h4 class="card-subtitle">Use your credentials</h4>
<dl> <!-- email FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="email">Email:<span class="required"> * </span></label>
</dt>
<dd>
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control"
placeholder="Your email address"
autocomplete=off
>
#error('form.email')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dt> email FIELD DEFINITION -->
<dl> <!-- password FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="password">Password:<span class="required"> * </span></label>
</dt>
<dd>
<input type="password"
wire:model.lazy="form.password"
id="password"
name="password"
class="form-control"
placeholder="Your password"
autocomplete=off
>
#error('form.password')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dl> password FIELD DEFINITION -->
</div> <!-- <div class="card-body card-block"> -->
<section class="card-footer row_content_right_aligned">
<button type="reset" class="btn btn-secondary btn-sm m-2">
Reset
</button>
<button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link">
Submit
</button>
</section>
</div> <!-- <div class="card"> -->
</form>
</article>
Which way is valid ?
Thanks in advance!
Before render method you can check if errorBag has items:
public function render()
{
if(count($this->getErrorBag()->all()) > 0){
$this->emit('error:example');
}
return view('livewire-component-view');
}
The beauty of Livewire is that you don't necessarily need to redirect to flash a message, you can display messages by setting properties on your component, and conditionally rendering them in your view. In this particular case, there's already logic readily available, you just have to check the errors-object being exposed by the validation.
In your view, all you have to do is check #if ($errors->any()) - if that's true, display your message. This is a Laravel feature, which Livewire implements. When any validation fails, an exception is thrown and intercepted, and the $errors variable gets exposed to your view. This means that whenver you do $this->validate(), and the validation fails, you can access the errors within $errors.
<div>
#if ($errors->any())
Check your login credentials
#endif
<form wire:submit.prevent="submit">
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<input type="password" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Submit</button>
</form>
</div>
Use the $rules attribute to declare the rules, validate those rules with $this->validate() and Livewire will do most of the work for you. You do not need to return any redirects, or use session()->flash(). The session-state will not be flashed, because you don't perform a new page load.
class Login extends Component
{
public $form = [
'email' => 'admin#mail.com',
'password' => '111111',
];
protected $rules;
private $view_name = 'livewire.auth.login';
public function submit()
{
$this->rules = User::getUserValidationRulesArray('login');
$this->validate();
// No need to do any more checks, $errors will now be updated in your view as the exception is thrown
// Proceed with submitting the form
After I used group middleware, I am not able to access error messages. Error bags returns empty.
There was no problem before.
I have researched, some users have solved the problem by changing http/kernel.php
\Illuminate\Session\Middleware\StartSession::class, $middlewareGroups to $middleware.
However, It doesn't work for me.
Also $validated = $request->validated(); function doesnt returns validation error. In my CreditcardRequest Class I have attributes, messages, rules functions. If validation fails these messages needs to be shown.
previously When validated(); method was running on the controller, it was showing the messages if the form is empty. I have 20 pages all of them working, before middleware grouping.
Creditcard Blade
<div class="messages">
#if ($errors->any())
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Error!</h3>
#foreach ($errors->all() as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
</div>
CreditcardRequest
public function attributes()
{
return [
'cc_name' => 'CC Owner',
..
];
}
public function messages()
{
return [
'required' => 'Required: :attribute',
...
];
}
public function rules()
{
return [
'cc_name' => 'required|max:128',
];
}
Controller
public function doPaySection(CreditcardRequest $request)
{
$validated = $request->validated();
$cc = TRUE;
if ($cc):
return redirect('/pay_success')->with('success', 'success');
else:
return redirect('/pay_error')->with('error', 'error');
endif;
}
web.php
Route::group(['middleware' => ['client.role:guest']], function () {
Route::get('/login', 'HomepageController#showLogin')->name('login');
Route::post('/login', 'HomepageController#doLogin');
Route::post('/register', 'HomepageController#doRegister');
Route::get('/register', 'HomepageController#showRegister')->name('register');
});
login.blade
#if ($errors->any())
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Hata!</h3>
#foreach ($errors->all() as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
Controller
public function doLogin(Request $request)
{
if (auth()->guard('client')->attempt(['email' => request('email'), 'password' => request('password')])) {
return redirect()->intended('/');
} else {
return redirect()->back()->with('error', 'error');
}
}
Can you try using this header in your request. Especially if you are hitting from postman.
Accept:application/json
Before using this, i was getting csrf token in case of invalid requests.
The code you have at the minute won't add a message to the $errors MessageBag, it will simply add a value to the session called error.
If you want to add an error to the message bag you could simply throw a ValidationException which redirect back with that message:
public function doLogin(Request $request)
{
if (auth()->guard('client')->attempt($request->only('email', 'password'))) {
return redirect()->intended('/');
}
throw ValidationException::withMessages([
'error' => 'The error message',
]);
}
Don't forget to import ValidationException with:
use Illuminate\Validation\ValidationException;
Your will be able to get in session('error')from below
return redirect()->back()->with('errors', 'error');
So your code would be like
#if (session('errors'))
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Hata!</h3>
#foreach (session('errors') as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
version: laravel 5.7
Router:
Route::get('regist','User\RegistController#registView');
Route::post('regist','User\RegistController#regist');
Form:
<form class="form-signin" method="POST" action="/regist">
.....
</form>
Validate:
$this->validator=Validator::make($input,$rule,$message);
if($this->validator->fails()){
return \Redirect::back()->withErrors($this->err());
}
The Problem:
Do not display an error message.Need to press Enter in the address bar to reload the page.Want to use the Validateor::make method.How can I modify it?
If the validation worked, did your put the error message to be displayed on the page you redirected to?
for example in your blade page did you do something like below?
#if(count($errors->all()) > 0)
<div class="alert alert-danger" role="alert">
<p><b>Required Fields Missing!</b></p>
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I will show you a simple example, if you are in the controller use the validator facade
use Illuminate\Support\Facades\Validator;
In the conroller user the below code
public function update(Request $request, $id) //use of request
{
$this->validate($request, [
'name' => 'required',
], [
'name.required' => 'Name is required',
]);
}
If validation fails it will automatically redirect back or you could use a validator fail statement and send a modified message.
After that you should put an if statement to display the error message as below:
#if(count($errors->all()) > 0)
<div class="alert alert-danger" role="alert">
<p><b>Required Fields Missing!</b></p>
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Or if you have only one defined error message use:
#if(Session::has('success'))
<div class="alert alert-success" role="alert">
{ Session::get('success') }}
</div>
#endif
Hope this helps
For add validation on form you can use Laravel Request Validation classes. which will help you to pull validation in separate class.
Here is the reference for request classes :- https://laravel.com/docs/5.7/validation#form-request-validation
That will help you to pull validation and also improvements in your code.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I am using Laravel 5.2 (although solutions for later versions are also okay).
I have a page, which contains BOTH the login page and registration page.
These forms use the AuthController as usual.
I display the errors like so:
#if (count($errors) > 0)
<div class="callout alert">
<strong>Whoops! Something went wrong!</strong>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
The issue is, the $errors variable does not make it clear which form the errors come from (i.e. Is it errors in the registration form or login form?).
How can I do this?
A way to handle this is to return flash messages. In your controller you can use something like:
For the login form
public function postLogin() {
// your code here
return redirect('/login')->with('login', 'Enter valid details');
}
For the sign up form
public function signUp() {
// your code here
return redirect('/login')->with('signup', 'SignUp has been successful');
}
And in order to display them in the view:
<div class="clearfix">
#if(Session::has('login'))
<div class="toast">
{{ Session::get('login') }}
</div>
#endif
</div>
<div class="clearfix">
#if(Session::has('signup'))
<div class="toast">
{{ Session::get('signup') }}
</div>
#endif
</div>