Make validate to be Only integer input in laravel - php

I need to make validate the (request_number) input is the Only integer and show a Message if the student writes a string as an example.
the Message if the user write the existing number is (the number of your order exists)
and the message if the user writes the non-integer value is (the input should be the Only Number)
Now I want to make double validation on (request_number).
this is my store in my controller
public function store(Request $request)
{
$excuse = new Student();
$excuse->request_number = $request->input('request_number');
$validatedData = $request->validate([
'request_number' => Rule::unique('students')->where(function ($query)
{
return $query->whereIn('status_id',[2,4,6,5]);
})]);
$excuse->student_id = Auth::guard('web')->user()->id;
$excuse->status_id = 1;
$excuse->college_id = Auth::guard('web')->user()->college_id;
$excuse->save();
return redirect('/students');
}
and this is my form to make a request
<form method="post" action="{{url('/student')}}" enctype="multipart/form-data">
#csrf
<h1> Make order FORM</h1>
<div class="form-group">
<label for="requestnumber"> write the Request Number </label><br>
<input type="text" id="request_number" name="request_number"class="form-control" minlength="5" style="width:50%" required >
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li> the number of request is exists </li>
#endforeach
</ul>
</div>
#endif
<br>
<button type="submit" class="btn btn-primary">send</button><br>
</form>

Try replacing your code with this
$status = Student ::whereIn('status_id', [2,3,4,5])->pluck
('status_id') ;
$validatedData = $request->validate([
'request_number ' =>
'required|integer ',
Rule::unique('students')->where(function ($query)
use ($status) {
return $query->whereIn('status_id', $status);
})
]) ;
and let me know either it is the thing you want or not

$validatedData = $request->validate([
'request_number ' => [
'required', 'integer', function($attr, $val, $fail) {
if (YourTargetModel::where('id', [1,2,3])->count() > 0) {
return $fail("The request number field should be
unique");
}
}]
]);

You can have many rules for a single field by using an array of rules:
'request_number' => [
'integer',
Rule::unique('students')->where(function ($query) {
return $query->whereIn('status_id', [2, 4, 6, 5]);
}),
]

Related

How do I redirect to another page after form submission in Laravel

form
When i submit the form it redirects back to the form itself, can anyone help me?
<form action="/jisajili" method="POST">
#csrf
<div class="card-panel z-depth-5">
<h5 class="center red-text">Jiunge Nasi</h5>
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="username" class="validate">
<label>Jina lako</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input type="number" name="phone" class="validate">
<label>Nambari ya simu</label>
</div>
....
</p>
<input type="submit" name="submit" value="Jiunge" class="btn left col s12 red">
Controller
class registration extends Controller{
public function create(){
return view('jisajili.jiunge');
}
public function store(Request $request){
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$cpassword = $request -> input('cpassword');
$reg->save();
$validated = $request->validate([
'name' => 'required|unique:posts|max:10',
'body' => 'required',
]);
return redirect('home');
}
}
What I would do is first check for the data requirements before you add the object to the database. Also I would add the columns of the models into the Model file to use the Object::create function with an array parameter.
I recomment to use routing in your blade file. I noticed you used action="/route". What you want to do is naming your routes with ->name('route_name') in the route files. To use them in your blade files with the global route function route="{{ route('route_name') }}".
<?php
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function store(\Illuminate\Http\Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|unique:posts|max:10',
'body' => 'required'
]
);
// Go back with errors when errors found
if ($validator->fails()) {
redirect()->back()->with($validator);
}
Post::create(
[
'name' => $request->get('name'),
'body' => $request->get('body')
]
);
return redirect()
->to(route('home'))
->with('message', 'The post has been added successfully!');
}
}
What you can do after this is adding custom errors into the controller or add them into your blade file. You can find more about this in the documentation of Laravel.
it redirects you back because of validation error.
change password confirmation name from cpassword into password_confirmation as mentioned in laravel docs
https://laravel.com/docs/7.x/validation#rule-confirmed
update your controller into:
public function store(Request $request){
$validated = $request->validate([
'username' => 'required',
'phone' => 'required',
'email' => 'required',
'password' => 'required|confirmed'
]);
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$reg->save();
return redirect('home');
}
in your blade add the following to display validation errors:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Populating edit form with db data returns Undefined variable Error - Laravel 7

I am working in Laravel 7 trying to auto populate form data from the db using value="{{ $task->task_name }}" for example. but it is throwing an Undefined Variable: task in my edit.blade.php file.
I am getting the right task id as I can see it in the url. I have tried {{ old('task_name') }} and that just returned a the placeholder in the input field with no error. if I put {{ old('task_name', $task->task_name) }} it also throws an error. If anyone can help out with this issue, I would certainly appreciate it. I am using resources for my functions. Here is the code so far:
edit.blade.php (just relevant portion)
<form method="POST" action="tasks/{$id}" id="editForm" enctype="multipart/form-data" class="mb-5">
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<input
id="task_name"
type="text"
name="task_name"
class="form-control"
placeholder="Task name"
value="{{ $task->task_name }}" />
</div>
...
<button type="submit" class="btn btn-success float-right">Edit Task</button>
</form>
In my tasks.blade.php (edit button only)
<div class="float-right" style="display: inline;">
<a href="tasks/{{$task->id}}/edit" class="btn btn-primary mb-3 ml-2">
<i class="fa fa-edit"></i> Edit
</a>
</div>
Finally, my TaskController.php
public function edit($id)
{
return view('tasks.edit');
}
public function update(Request $request, $id)
{
$this->validate($request, [
'task_name' => 'required',
'task_description' => 'required',
]);
$task = Task::find($id);
$task->task_name = $request->input('task_name');
$task->task_description = $request->input('task_description');
$task->task_priority = $request->input('task_priority');
$task->task_assigned_by = $request->input('task_assigned_by');
$task->task_assigned_to = $request->input('task_assigned_to');
$task->task_to_be_completed_date = $request->input('task_to_be_completed_date');
$task->task_notes = $request->input('task_notes');
$task->task_status = $request->input('task_status');
$task->update();
return redirect('/tasks')->with('success', 'Task Updated');
}
If I am missing any code or if you have any questions that would shed light on my query, please let me know so I can update my question. Thank you again in advance.
You need to pass the $task variable into the view:
public function edit($id)
{
$task = Task::findOrFail($id);
return view('tasks.edit', ['task' => $task]);
}
Also, you can use the request validation method to extract the inputs that you need, after that, everything will be in the $data variable and you can easily update your model with one line of code.
I don't know how do you expect to receive the data, so I use nullable for the validation entries, you can take a look into all validations here: https://laravel.com/docs/7.x/validation
public function update(Request $request, $id)
{
$task = Task::findOrFail($id);
$data = $request->validate([
'task_name' => 'required',
'task_description' => 'required',
'task_priority' => 'nullable',
'task_assigned_by' => 'nullable',
'task_assigned_to' => 'nullable',
'task_to_be_completed_date' => 'nullable',
'task_notes' => 'nullable',
'task_status' => 'nullable',
]);
$task->update($data);
return redirect('/tasks')->with('success', 'Task Updated');
}
This code will make the same this as the other, but it's much cleaner in my opinion.

Multi-step form in Laravel

I am trying to create a multi-step form for a user to fill after logging in. I created separate pages with forms that will be a part of the common form.
The data will be saved in the "users" table.
I am new to Laravel and I followed this: https://www.5balloons.info/multi-page-step-form-in-laravel-with-validation/
In my FormController I have these methods:
public function index(Request $request)
{
$request->session()->forget('user');
$user = User::all();
return view('form.index',compact('user',$user));
}
public function updateStep1(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step1',compact('user', $user));
}
public function postupdateStep1(Request $request)
{
$validatedData = $request->validate([
'first_name' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/update-step2');
}
public function updateStep2(Request $request)
{
$user = $request->session()->get('user');
return view('form.update-step2',compact('user', $user));
}
public function postupdateStep2(Request $request)
{
$validatedData = $request->validate([
'address' => 'required',
]);
if(empty($request->session()->get('user'))){
$user = User::where('id',auth()->user()->id)->first();
$user->fill($validatedData);
$request->session()->put('user', $user);
}else{
$user = $request->session()->get('user');
$user->fill($validatedData);
$request->session()->put('user', $user);
}
return redirect('/form/store');
}
public function store(Request $request)
{
$user = User::where('id',auth()->user()->id)->first();
$user = $request->session()->get('user');
$user->save();
return redirect('/form');
}
And these are the Routes:
Route::get('/form', 'FormController#index');
Route::get('/form/update-step1', 'FormController#updateStep1');
Route::post('/form/update-step1', 'FormController#postupdateStep1');
Route::get('/form/update-step2', 'FormController#updateStep2');
Route::post('/form/update-step2', 'FormController#postupdateStep2');
Route::post('/form/store', 'FormController#store');
This is the first part of the form:
#extends('layouts.app')
#section('content')
<h1>update - Step 1</h1>
<form action="/form/update-step1" method="post">
#csrf
<div class="form-group">
<label for="name">First Name</label>
<input type="text" value="{{ old('first_name', $user->first_name ?? null) }}" class="form-control" name="name">
</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">Continue</button>
</form>
#endsection
I get an error when I try to submit, saying that the fields are required. So even if I do enter a name etc., it doesn't work. If I delete the validations, it seems like everything works but no data is added to the database.
Any suggestions?
You should use the input name is first_name because you have used first_name in the validation.
<input type="text" value="{{ old('first_name', $user->first_name ?? null) }}" class="form-control" name="first_name">
OR
If want to change name value in the user table:
FormController
$validatedData = $request->validate([
'name' => 'required',
]);
first part of the form:
<input type="text" value="{{ old('name', $user->name ?? null) }}" class="form-control" name="name">

form input cleared after submit data using laravel fram work

I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$product=new productModel();
// start add
$product->name = $request->input('name');
$product->save();
$add = $product->id;
$poducten = new productEnModel();
$poducten->id_product = $add;
$poducten->name = $request->input('name');
$poducten->price = $request->input('price');
$poducten->save();
$dataview['message'] = 'data addes';
} else {
$dataview['message'] = 'name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.

Passing Data through Return Redirect Back to Update Request

I am trying to allow a user to update their information after they have submitted a form, but did not check a certain box. Everything is within the same page and I am controlling the different modals by returning a message, which triggers a script to open the different modals.
For some reason, I can't seem to pass the ID or email through to the next step. Can anyone help with this?
Whenever, I try, I get the following error:
Undefined variable: leads
Any idea?
Thanks!!!
Files:
web.php
index.blade.php
LeadsController.php
Leads.php
Web.php
Route::post('/', [
'uses' => 'LeadsController#store',
'as' => 'leads.store'
]);
Route::patch('/{email}', [
'uses' => 'LeadsController#update',
'as' => 'leads.update'
]);
Index.blade.php
<html>
<div id="contact" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form id="form" class="form" action="/" method="post" accept-charset="utf-8">
{{ csrf_field() }}
<input type="email" name="email" value="{{ old('email') }}">
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#if(session()->has('message'))
<div id="sign_up" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form method="post" action="{{ route('leads.update', $leads->email) }}">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#endif
</body>
</html>
LeadsController.php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->all);
} else {
try {
$leads = new Leads;
$leads->email = $request->email;
$leads->newsletter = $request->newsletter;
$leads->save();
if($request->newsletter == ''){
return redirect()->back()->with('message','sign up')->withInput($request->all)->with($leads->email, $request->get('email'));
}
if($request->newsletter == 'true'){
return redirect()->back()->with('success','success');
}
} catch (Exception $e) {
return response()->json(
[
'status' => false,
'error' => base64_encode($e->getMessage()),
],
Status::HTTP_INTERNAL_SERVER_ERROR
);
}
}
}
public function update($email)
{
$leads = Leads::find($email);
$leads->newsletter = $input('newsletter');
$leads->save();
return redirect()->back()->with('success','success');
}
Leads.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Leads extends Model
{
protected $table = 'my_renamed_table';
public $timestamps = false;
protected $fillable = ['email', 'newsletter'];
}
Thanks for all of your help and your questions! You helped push me in the right direction.
Here is how I solved it:
I had to correct myself in how I pushed the $email through to the view:
LeadsController
return redirect()
->back()
->with('message','sign up')
->withInput($request->all)
->with('email', $request->get('email'));
Notice how I'm sending the email through as 'email' here.
Then, I pushed the email through the view in the 2nd form like this:
index
<form method="post" action="{{ route('leads.update', session('email')) }}">
Then, finally, in order to capture the email again, use it to find the lead that I wanted, I had to drastically change the update:
public function update($email)
{
DB::table('my_renamed_table')
->where('email', $email)
->update(['newsletter' => Input::get('newsletter')]);
return redirect()->back()->with('success','success');
}
Thanks again!

Categories