I am using laravel 8
I want to make when the validation error , it will show the sweetalert or session message when error to the index page just like this
{{-- Flash data --}}
#if(session()->has('success'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ session('success') }}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
but in my controller have an error here's in my controller
public function verify(VerifyRequest $request)
{
// Verify using VerifyRequest
$validated = array_merge($request->validated(), ['token' => Str::random(127)]);
// the error in this line
if($validated->validate()->fails()){
return redirect(url()->previous() . '#verify-email')->withErrors($request)->withInput();
}
// end the error
// create
Pengaduan::create($validated);
// Setup the email message
$data = [
'content' => 'to create complaint please click the link below',
'url' => 'http://127.0.0.1:8000/complaint/create/' . $validated['token'],
];
// Send to email
Mail::to($validated['email'])->send(new VerifyAlternative($data));
return redirect()
->route('complaint.check')
->with('success', 'Register success. Please Check your email');
}
#endif
here's in my VerifyRequest
class VerifyRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => ['required', Rule::unique('complaints')],
];
}
public function messages()
{
return [
'email.unique' => 'This email is making a Complaint. Wait for the complaint to be completed to make a complaint again'
];
}
protected function prepareForValidation()
{
$this->merge([
'email' => $this->email . '#univesity.com',
]);
}
}
Can anyone help me to solve this as soon as posible. Thank you in advanced
Related
I am working in Laravel.
I have a URL like as below:
http://localhost/udonls/public/mastercandidate/candidate/reset-password/11/das#sdadas.com
Now has a function which is like
public function sendCanResLink(Request $request, $id, $email)
{
// So in this function how should i validate "$email" using laravel validation ?
}
Here is the route:
Route::get('/candidate/reset-password/{id}/{email}', [
'as' => 'candidate.reset.password',
'uses' => 'CandidateSmdnContoller#sendCanResLink'
]);
Overall !! I want to validate my email address which I get in the GET request in larvae with Laravel validation.
I know regex technique but I want to use the Laravel validation technique.
Maybe something like this:
public function sendCanResLink(Request $request, $id, $email)
{
try {
$validator = Validator::make($email, [
"email" => "required|email:rfc,dns,filter,spoof",
]);
} catch(ValidationException $validation) {
return redirect()->back();
}
}
Why spend resources on validation in this case, if you can check one on one for the user?
Route::get('/candidate/reset-password/{user}/{email}', [
'as' => 'candidate.reset.password',
'uses' => 'CandidateSmdnContoller#sendCanResLink'
]);
public function sendCanResLink(Request $request, User $user, $email)
{
if($user->email !== $email) return 'some error';
// reset code here
return 'ok';
}
2) With validator
public function sendCanResLink(Request $request, $id, $email)
{
Validator::make(compact('email'), [
'email' => ['required', 'string', 'regex:/[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/', 'max:255', 'unique:YOUR_TABLE']
])->validate();
// auto redirect back if error and use
// #error('email') {{ $message }} #enderror in blade
}
I am developing collaborators adding methods to my project management application. this is my collaborators add form.
colllaborators/form.blade.php
<div class="col-md-4" style="border:1px solid #ccc;margin-left:15px;padding:10px;">
<h4 class="page-header">
Collaborators
</h4>
#if( $collaborators)
#foreach( $collaborators as $collaborator)
<div>
<div>
<span>
<img src="{{ $collaborator->user()->first()->getAvatarUrl() }}" />
</span>
</div>
<button class="btn btn-sm btn-danger delete" style="margin-top:5px;padding:4px;width:35px;"
data-action="/projects/{{ $project->id }}/collaborators/{{ $collaborator->collaborator_id }}"
routes
Route::post('projects/{projects}/collaborators', [
'uses' => 'Project\Collaborators\Controller#addCollaborator',
'as' => 'projects.collaborators.create',
'middleware' => ['auth']
]);
but when I click to collaborators adding buttons following error messages displayed.
Undefined variable: collaborators (View: C:\Users\Flex\Desktop\ddd\resources\views\collaborators\form.blade.php)
how can I fix this problem
edited
class ProjectCollaboratorsController extends Controller
{
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->back()->with('info', "{$collaborator_username} has been added to your project successfully");
}
private function getId($username)
{
$result = User::where('username', $username)->first();
return (is_null($result)) ? null : $result->id;
}
private function isCollaborator($projectId, $collaboratorId)
{
return Collaboration::where('project_id', $projectId)
->where('collaborator_id', $collaboratorId)
->first();
}
}
see My other part of the form
<form class="form-vertical" role="form" method="post" action="{{ route('projects.collaborators.create', $project->id) }}">
collaborator form route
Route::get('/collaborators', function(){
return view('collaborators.form');
})->name('collaborators.form');
In your form page, you are checking #if( $collaborators) which checks if the $collaborators variable is not empty and then runs the foreach below it.
After you submit your form, you add the collaborator and redirect back with no collaborators. The if condition then tries to check if the variable is empty. At this point the variable has not been defined and hence it throws that error. To fix this error, return redirect back with the collaborators like this:
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->back()->with(['collaborators'=>$collaborators,'project'=>$project,'info'=> "{$collaborator_username} has been added to your project successfully"]);
}
EDIT:
Using the with method puts the data in the session, i would suggest that you manually redirect to the view and flash the message to that view.
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
if( is_null($this->getId($collaborator_username)))
{
return redirect()->back()->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->back()->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
//Get all collaborators
$collaborators = Collaboration::all(); //if this is how you get all collaborators
//Get the project too
$project = Project::findOrFail($id);
return redirect()->route('collaborators.form',['collaborators'=>$collaborators,'project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
Edit 2
I have changed all the return redirect()->back()'s
public function addCollaborator(Request $request, $id, Collaboration $collaboration)
{
$this->validate($request, [
'collaborator' => 'required|min:5',
]);
$collaborator_username = substr(trim($request->input('collaborator')),1);
$collaboration->project_id = $id;
//Get the project too
$project = Project::findOrFail($id);
if( is_null($this->getId($collaborator_username)))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user does not exist');
}
$collaborator = $this->isCollaborator($id, $this->getId($collaborator_username));
if(! is_null($collaboration))
{
return redirect()->route('collaborators.form',['project'=>$project])->with('warning', 'This user is already a collaborator on this project');
}
$collaboration->collaborator_id = $this->getId($collaborator_username);
$collaboration->save();
return redirect()->route('collaborators.form',['project'=>$project])->with('info',"{$collaborator_username} has been added to your project successfully");
}
And change your routes to
Route::get('/project/{project}/collaborators', function($id){
$collaborators = Collaboration::all();
$project = Project::findOrFail($id);
return view('collaborators.form',compact('collaborators','project'));
})->name('collaborators.form');
So I am receiving data from a form that should reset user passwords:
Old Password: |field|
New Password: |field|
Confirm Password: |field|
And i want to be able to display a message out for the user if his old password does not match what he entered in the first field. I don't want to make an entirely new validation method and just want to throw an error to the use when i make my own if(). So how do I achieve this using the $errors variable that is available in my blade views
So here is an example of my controllers method
public function update(Request $request){
$this->validate($request,[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
$user = Auth::user();
if(password_verify($request->newPass,$user->password)){
$user = User::find($user->id);
$user->password = bcrypt($request->newPass);
$user->save();
}else{
//the code for adding a new key to $errors variable
return back(); Or return redirect('path');
}
}
So in the view I want to this
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
You can do this in your controller:
$validator = Validator::make($request->all(),[
'oldPassword' => 'required',
'password' => 'required|min:8|confirmed'
]);
And then before your return back();, add:
$validator->after(function($validator) {
$validator->errors()->add('tagName', 'Error message');
});
With your message.
i'm trying to use callback to simply to check my form input, the offical code is here: https://laravel.com/docs/5.2/validation
the following is my function
public function addthread(Request $request) {
$input = $request->all();
$rules = array('title' => 'required|unique:thread|max:255');
$message = array('title.required' => 'The :attribute field is aaa required.');
$validator = Validator::make($input, $rules, $message);
$validator->after(function($validator) {
if ($this->checkOpt()) {
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
});
if ($validator->fails()) {
return redirect('addthreadhtml')->withErrors($validator)->withInput();
}
}
public function checkOpt() {
return false;
}
the blade tpl:
#if (count($errors) > 0)
<div class="container" stytle="max-width:80%">
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
The num_opt error never print out, any idea?
checkOpt() is returning FALSE, so the code will never enter the if statment.
if ($this->checkOpt()) { // this is returning false, right ?? so, its not adding the error
$validator->errors()->add('num_opt', 'Something is wrong with this field!');
echo 'test';
}
Your checkOpt() always returns false, so your condition won't ever be satisfied.
Hi Im using a repository pattern in laravel and to create tasks and they all have an estimated time and the project has a capacity of hours. So i need to pass this back when the task is created so they can see how many hours are left.
I have this so far:
TaskRepository.php
public function createTask(array $attributes)
{
if ($this->validator->createATask($attributes)) {
$newAttributes = [
'project_id' => $attributes['project_id'],
'estimated_time' => $attributes['estimated_time'],
'task_name' => $attributes['task_name']
];
$task = Task::updateOrCreate([
'task_name' => $attributes['task_name']
],
$newAttributes);
$task->save();
$project = Project::find($attributes["project_id"])->pluck('capacity_hours');
$tasks = Task::find($attributes["project_id"])->lists('estimated_time');
$tasksTotal = array_sum($tasks);
$capcity_left = ($project - $tasksTotal);
return $capcity_left;
}
throw new ValidationException('Could not create Task', $this->validator->getErrors());
}
and in my controller I have this:
TaskController.php
public function store() {
try {
$this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
if (Request::ajax()) {
return Response::json(['errors' => $e->getErrors()], 422);
} else {
return Redirect::back()->withInput()->withErrors($e->getErrors());
}
}
if (Request::ajax()) {
return Response::json(["message" => "Task added",'capcity_left'=> $capcity_left]);
} else {
return Redirect::back()->with('success', true)->with(['message', 'Task added', 'capcity_left'=>$capcity_left ]);
}
}
and I have a partial for errrors:
#if(Session::get('success'))
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
aria-hidden="true">×</span></button>
<strong>{{ Session::get('message', '') }} Capacity Left:{{ Session::get('capcity_left', '') }}</strong>
</div>
#endif
However I get this error:
Undefined variable: capcity_left
Any ideas how I can pass this back to the controller? I thought I was by saying return $capcity_left; Do I need to catch this in the controller? If so how can I do that?
You forgot to assign the return value of the createTask method when calling it from the controller. So you need to do this:
public function store() {
try {
// assign the return value here
$capcity_left = $this->task_repo->createTask(Input::all());
} catch (ValidationException $e) {
// ...
}