Form array validation Laravel 5.2 - php

I am currently stuck on solving this problem. I am new to Laravel and the MVC framework. I am struggling to create the dynamic form that gives the user the ability to add as many forms as possible. When the user enters the page at first it generates 5 form fields . Here is a look at my code so far.
<div id ={{$id = "from".$i}} >
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name = "address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address"> <!-- problem form array how does this work in laravel -->
</div>
<div class="form-group col-md-6">
<label for={{$id = "city".$i}}>City</label>
<input type="text" value = "{{ old('city') }}" class="form-control" id={{$id = "City".$i}} placeholder="City">
#if ($errors->has('city'))
<span class="help-block">
<strong>{{ $errors->first('city') }}</strong>
</span>
#endif
</div>
How would I go about validating a form in Laravel 5.2 with from array
here's my controller
public function Postdata(Request $request) {
$this->validate($request->all(), [
'address.*' => 'required|string',
'city' => 'required',
]);
}
I am using a for loop to generate the forms dynamically.
here is the error I get
ErrorException in ValidatesRequests.php line 49:
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, array given, called in
C:\wamp\www\Dynamic- 1.0\app\Http\Controllers\propContoller.php on line 34 and defined
Can someone please help or point me in the right direction thank you !

add name="city[{{$i}}]"
Create a specific request with php artisan make:request PostRequest
Change public function Postdata(Request $request) { to public function Postdata(PostRequest $request) {
Remove the validate function call from your controller
Go to /app/Http/Requests/PostRequest.php
Then edit the rules function to something like this ...
.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
foreach($this->request->get() as $key => $val)
{
$rules['address.' . $key] = 'required';
$rules['city.' . $key] = 'required';
}
return $rules;
}

Thank You man ! this is the solution I end up with
<div class="form-group col-md-6">
<div class="col-md-6 form-group">
<label for={{$id = "Address".$i}}>Address</label>
<input type="text" name="address[{{$i}}]" class="form-control" id={{$id = "Address".$i}} placeholder="Street Address">
</div>
in post request i did this
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
$rules = [];
foreach($this->request->get('address') as $key => $val) {
$rules['address.'.$key] = 'required';
}
return $rules;
}

Related

How to display the value in a readonly input field in laravel

So, in my project, a user needs to register first before logging-in. I am trying to display their first, middle and last name. But, I am having a problem since multiple data are displayed on my input field. What is the correct query? Here is my controller code
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$input.="<input value={$first_name->seq_id}>{$first_name->first_name}</input>";
}
return $input;
}
public function step1()
{
$users = UserModel::all();
$data['optStatus']=$this->get_civil_status();
$data['displayFirstName']=$this->get_first_name();
return view ("enrollment-steps.step1", $data);
}
Here is the blade file
<div class="col-sm-12 col-lg-4">
<div class="form-group row">
<label for="firstName" class="col-sm-3 text-right control-label col-form-label">First
Name</label>
<div class="col-sm-9">
<input class="form-control" type="text" id='firstName' readonly value="{!! $displayFirstName !!}" >
</div>
</div>
</div>
this is the data that it displays
There is some confusing stuff going on there, but you probably want
<input class="form-control" type="text" id='firstName' readonly value="{{ $data['displayFirstName'] }}" >
which will display the value with the key 'displayFirstName' in the $data array.
dd is your friend, use this in your blade file to see what you have in your $data variable.
{{dd($data)}}
In you controller bind the data's in a single variable, then show it in the blade
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$input.="<input value={$first_name->seq_id}>{$first_name->first_name}</input>";
}
return $input;
}
Instead of this, do something like this:
public function get_first_name()
{
$first_names = UserModel::all();
$input="<input></input>";
foreach($first_names as $first_name)
{
$displayname = $first_name->seq_id . $first_name->first_name;
$input.="<input value="{$displayname}"</input>";
}
return $input;
}

Uploading image from input field and still getting validation error saying that field is required

Route Code:
Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function(){
Route::resource('gallery', GalleryController::class);
});
The Form I'm Using to Upload the File:
<form action="{{ route('gallery.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" name="gallery_img" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
#error('gal_img')
<span class="text-danger">{{ $message }}</span>
#enderror
<div class="input-group-append">
<div class="col-sm-10" style="padding-left: 1px;">
<button type="submit" class="btn btn-dark">Save</button>
</div>
</div>
Controller Code:
public function store(GalleryRequests $request)
{
$gal_img = $request->file('gallery_img');
$gal_file = date('YmdHi').$gal_img->getClientOriginalName();
$gal_img->move(public_path('upload/gallery'), $gal_file);
$save_path = 'upload/gallery/'.$gal_file;
Gallery::insert([
'gal_img' => $save_path
]);
$notification = array(
'message' => 'Slider Inserted Successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Request file validation:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gal_img' => 'required'
];
}
public function messages(){
return [
'gal_img.required' => 'Please Select an Image First',
];
}
The error I get when trying to save after selecting an Image:
Trying to figure out what I've done wrong for hours and am so frustrated right now, please help me to resolve this issue.
Thanks in advance.
Field in form is named gallery_img so that name has to be checked:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gallery_img' => 'required'
];
}
public function messages()
{
return [
'gallery_img.required' => 'Please Select an Image First',
];
}

Laravel 8 - How to suppress validation errors with a back button in Laravel

How to suppress validation errors with a back button in Laravel ??
Details: I have form with two buttons and I made validation how to skip validation when click on (back-button)?
the code in the view page:
<form method="POST" action="{{route("movies.store")}}" class="mt-5 w-50 m-auto">
#csrf
<div class="mb-3">
<label class="form-label">Movie Name</label>
<input type="text" name="movie_name" class="form-control">
#error('movie_name')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Descrption</label>
<input type="text" name="movie_description" class="form-control">
#error('movie_description')
<span class="error">{{$message}}</span>
#enderror
</div>
<div class="mb-3">
<label class="form-label">Movie Gener</label>
<input type="text" name="movie_gener" class="form-control">
#error('movie_gener')
<span class="error">{{$message}}</span>
#enderror
</div>
<button type="submit" name="action" value="back" class="btn btn-warning me-3">Back</button>
<button type="submit" name="action" value="add" class="btn btn-primary">Add</button>
</form>
the code in the controller file:
public function store(MoviesFormRequest $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
$data = $request->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}
If you just want to solve the problem by implementing back button instead of using button tag use anchor tag as follows
Back
And remove the switch statement and just do as follows:
public function store(MoviesFormRequest $request)
{
Movie::create($request->all());
return redirect()->route("movies.index");
}
Inside your MoviesFormRequest class do all the validations like :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MoviesFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'movie_name' => 'required',
'movie_description' => 'required',
'movie_gener' => 'required',
];
}
}
This will work for you just customize the anchor tag to look good. Hope this solve your problem.
The validation happens in your custom request (MoviesFormRequest) before the code in the controller method is executed.
So in order to skip validation given a specific request input, you have to make the it part of the switch block
use Illuminate\Http\Request;
// use the base request here (no validation at this point)
public function store(Request $request)
{
switch ($request->input('action')) {
case 'back':
return redirect()->route("movies.index");
case 'add':
// in our case block we can validate
$this->validate($request, [
'title' => ['required'],
//... your rules here
]);
$data = $this->validated();
Movie::create($data);
return redirect()->route("movies.index");
}
}

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.

Edit profile page using laravel

Whenever a user goes to mywebsite.com/profile I want a form to pre populate the values they've entered during the signup/registration flow. I was able to do that with my form here
<h1><b>Your Profile</b></h1>
<form method="POST" action="/profile/update">
<div class="form-group hidden">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="_method" value="PATCH">
</div>
<div class="form-group {{ $errors->has('name') ? ' has-error' : '' }}">
<label for="email" class="control-label"><b>Name:</b></label>
<input type="text" name="name" placeholder="Please enter your email here" class="form-control" value="{{ $user->name }}"/>
<?php if ($errors->has('name')) :?>
<span class="help-block">
<strong>{{$errors->first('name')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group {{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="control-label"><b>Email:</b></label>
<input type="text" name="email" placeholder="Please enter your email here" class="form-control" value="{{ $user->email }}"/>
<?php if ($errors->has('email')) :?>
<span class="help-block">
<strong>{{$errors->first('email')}}</strong>
</span>
<?php endif;?>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default"> Submit </button>
</div>
</form>
But now im running into the issue if the user just hits submit button without changing any fields, laravel's built in validations checks and gives me an error message of The name has already been taken. which is true. so im not sure how to handle this issue, but here is my controller below
<?php
namespace App\Http\Controllers;
use Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class ProfileController extends Controller
{
/**
* Update user profile & make backend push to DB
*
**/
public function index() {
/**
* fetching the user model
**/
$user = Auth::user();
//var_dump($user);
/**
* Passing the user data to profile view
*/
return view('profile', compact('user'));
}
public function update(Request $request) {
/**
* Validate request/input
**/
$this->validate($request, [
'name' => 'required|max:255|unique:users',
'email' => 'required|email|max:255|unique:users',
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('name','email');
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Accessing the update method and passing in $input array of data
**/
$user->update($input);
/**
* after everything is done return them pack to /profile/ uri
**/
return back();
}
}
and here is my routes file.
// only authenticated users
Route::group( ['middleware' => 'auth'], function() {
Route::get('/home', 'HomeController#index');
// practicing using forms for sending data to the DB & populating form fields with DB data
Route::get('profile', 'ProfileController#index');
Route::patch('profile/{id}', 'ProfileController#update');
});
Issue is due to unique validation rule. You can exclude the current user id by specifying unique validation rule. your code will be like this
public function update(Request $request) {
/**
* fetching the user model
*/
$user = Auth::user();
/**
* Validate request/input
**/
$this->validate($request, [
'name' => 'required|max:255|unique:users,name,'.$user->id,
'email' => 'required|email|max:255|unique:users,email,'.$user->id,
]);
/**
* storing the input fields name & email in variable $input
* type array
**/
$input = $request->only('name','email');
/**
* Accessing the update method and passing in $input array of data
**/
$user->update($input);
/**
* after everything is done return them pack to /profile/ uri
**/
return back();
}
here is laravel documentation link for this https://laravel.com/docs/5.1/validation#rule-unique

Categories