I have input as shown below:
<input name="keyword[]" type="text" id="keyword" value="" ... required>
<input name="url[]" type="text" id="url" value="" ... required>
This is the result of input request to form an array in it:
array:4 [▼
"_token" => "LSgeBGHL6QQEkirJFcSLC4T045vb2M4afsi48NeC"
"category_id" => "1266"
"keyword" => array:2 [▼
0 => "test"
1 => "test"
]
"url" => array:2 [▼
0 => "/search/test"
1 => "/search/test"
]
]
I want to make a validation if the input array is the same and the data is already in the database before it will not be able to input. I have tried using validation as below, but it didn't work and got an error message.
public function postAdd()
{
$data = \Input::all();
$this->validate($data, [
'keyword.*' => 'required|sometimes|unique',
'url.*' => 'required|sometimes|unique'
]);
}
Please help me to be able to make the same input validation in the array and validate if the inputted data already exists in the database. Thanks!
'keyword.0' => 'required|unique:tablename,fieldname',
'keyword.1' => 'required|unique:tablename,fieldname',
This how to access an validate each member of the array.
I guess I forgot to add if input are same.
'keyword.0' => 'required|unique:tablename,fieldname|different:keyword.1',
Related
I have a form that submits an array named prazos, and I want to make sure each item is a valid datetime or null. Following the answers to this question and the Laravel docs, I have this in my Controller:
use Illuminate\Support\Facades\Validator;
// ...
$rules = array([
'prazos' => 'required|array',
'prazos.*' => 'nullable|date'
]);
$validator = Validator::make($request->all(), $rules);
$data = $validator->valid()['prazos'];
foreach($data as $id => $prazo) {
// use $data to update my database
// ...
}
The issue is, the validator is not actually stopping invalid content. If I try to submit "loldasxyz" or other gibberish, I get an error from the database. What am I doing wrong?
Note: previously I had been using validators with the syntax $data = $request->validate($rules), but for some reason it didn't work for the array-type data ($data came back empty). I'm not sure if there is some difference in how those different methods work.
Edit: this is what the parameter bag in $request looks like when I test it (the indices are ids, which is why they start at 1):
#parameters: array:3 [▼
"_token" => "Rf6mAp4lqhpZzQRxaxYsees1M0NfrFKpbGe4Hy28"
"_method" => "PUT"
"prazos" => array:5 [▼
1 => "2021-03-22 21:21"
2 => "2021-03-03 11:27"
3 => "jhbkjhg"
4 => null
5 => "2021-03-02 14:21"
]
]
And this is what the validated $data comes out as:
array:5 [▼
1 => "2021-03-22 21:21"
2 => "2021-03-03 11:27"
3 => "jhbkjhg"
4 => null
5 => "2021-03-02 14:21"
]
I wish it would tell me the third value is invalid.
Heres what youre looking for:
https://laravel.com/docs/8.x/validation#rule-date-equals
The field under validation must be equal to the given date. The dates will be passed into the PHP strtotime function in order to be converted into a valid DateTime instance.
I have tried searching for something similar to the question above but no luck.
I have a one to many relationship between a series and videos table. Inside the videos table I have title and url to the video.
The issue i am having is that, i am using jquery to add multiple rows containing title and url.
I tried pushing the title and url to the videos table on the database. There's no problem when pushing one input but when i have many title and url, the code breaks.
I have also tried using createMany but it can only add an array of one input. I can't get it to add both title and url.
$data = \request()->validate([
'title' => 'required',
'vimeo_id' => 'required',
'episode_number' => 'required'
]);
$pricourse->videos()->createMany($data);
After i dd the data in the browser i got the following
array:4 [▼
"_token" => "82k5RnVcdzSkPoOnDYeYipuRqAcJqhXzcWAx3RwW"
"title" => array:2 [▼
0 => "Angles of Elevation"
1 => "English 2"
]
"vimeo_id" => array:2 [▼
0 => "12343"
1 => "12343"
]
"episode_number" => array:2 [▼
0 => "1"
1 => "2"
]
]
Any help will be appreciated..
Thanks
createMany() is the way to go as far as I can understand. You are probably doing it wrong.
Here is an example :
$videosToCreate = [
[
'title' => 'title number 1',
'url' => 'some url number 1'
],
[
'title' => 'title number 2',
'url' => 'some url number 2'
],
[
'title' => 'title etc...',
'url' => 'some url etc...'
]
];
$this->videos()->createMany($videosToCreate);
We cannot help you if you do not share any code though.
I discovered i was not passing the data from the hmtl page properly. I made a few changes to it.
<input type="text" name="videos[0][title]">
<input type="text" name="videos[0][vimeo_id]">
<input type="text" name="videos[0][episode_number]">
<input type="text" name="videos[1][title]">
<input type="text" name="videos[1][vimeo_id]">
<input type="text" name="videos[1][episode_number]">
My controller code goes below
$data = \request()->validate([
'videos.*.title' => 'required',
'videos.*.vimeo_id' => 'required',
'videos.*.episode_number' => 'required'
]);
$pricourse->videos()->createMany($data['videos']);
All i had to do was pass $data['videos'] inside createMany
Thank you all for your help. It served as a pointer
I've got the following validation rules for basic authentication of a Payment Method (advanced things, like CVD validation, existing card, etc. is handled afterward by Moneris).
$rules = [
"type" => "required|in:visa,mastercard",
"nickname" => "required",
"credit_card_number" => "required|numeric|digits:16",
"expiry" => "required|string|size:5|date_format:m/y|after:today",
"cvd" => "required|numeric|digits:3"
];
The rule expiry is not accepting a specific value, 04/yy, but it is accepting 03/yy and 05/yy; I have no idea why this is happening, but I need it remedied. Has anyone come across this behaviour?
For reference, the result dd($request->input(), $validator->passes(), $validator->errors()); when I pass 04/19 is as follows:
array:6 [▼
"type" => "visa"
"nickname" => "Testing"
"credit_card_number" => "4242424242424242"
"expiry" => "04/19"
"cvd" => "123"
"masked_pan" => "************4242"
]
false
MessageBag {#502 ▼
#messages: array:1 [▼
"expiry" => array:1 [▼
0 => "The expiry does not match the format m/y."
]
]
#format: ":message"
}
When I send 05/19, everything works fine:
array:6 [▼
"type" => "visa"
"nickname" => "Testing"
"credit_card_number" => "4242424242424242"
"expiry" => "05/19"
"cvd" => "123"
"masked_pan" => "************4242"
]
true
MessageBag {#502 ▼
#messages: []
#format: ":message"
}
Looks like it's an issue with how this validation rule works in Laravel 5.4. To fix, I check the date validity of the input prepended with 01/, and if it is valid, merge that into the request, with endOfMonth() to handle after:today validation:
$mergeDate = null;
$rawInput = $request->input("expiry");
try {
$mergeDate = Carbon::createFromFormat("d/m/y", "01/".$request->input("expiry"))->endOfMonth();
} catch(\Exception $ex){}
$request->merge([
"masked_pan" => str_repeat("*", 12).substr($request->input("credit_card_number", ""), -4),
"expiry" => $mergeDate ? $mergeDate->format("d/m/y") : $request->input("expiry")
]);
So now, if I pass 04/22, it will check if 01/04/22 is valid, then convert to end of month 30/04/22, then replace that as the value passed to the validation (which also needs to be updated)
"expiry" => "required|string|size:8|date_format:d/m/y|after:today",
I also have to update and pass $messages to avoid confusion to the user:
$messages = [
"expiry.size" => "The :attribute filed must be 5 characters.",
"expiry.date_format" => "The :attribute field does not match the format m/y"
];
$validator = \Validator::make($request->all(), $rules, $messages);
And finally, replace the value with the raw input if there's an error (so the user doesn't see a value they didn't enter)
if(!$validator->passes()){
$request->merge(["expiry" => $rawInput]);
return back()->withErrors($validator)->withInput();
}
A whole bunch of nonsense, but seems to handle 04/22 and other dates just fine.
i am building a laravel aplication and i have this line of code which should redirect the user back to form he just submited , with the old input and the result of some operations .
return back()->with(["result" => round($area, 2)])->withInput($request->all());
The problem is that i only receive the old input in blade and the $result variable is not available in the view.
This is how i try to output the result:
<input type="text" name="result" value="{{isset($result)&&old('roofType')==0?$result:''}} ㎡ " class="form-control input-sm" >
And here is what variables i have in the view after submit:
{{ dd(get_defined_vars()['__data']) }}:
array:7 [▼
"__env" => Factory {#89 ▶}
"app" => Application {#3 ▶}
"errors" => ViewErrorBag {#169 ▶}
"roofName" => "Acoperis intr-o apa"
"roofType" => "1"
"roofFolder" => "A1"
"baseFields" => array:3 [▼
0 => "L"
1 => "l"
2 => "H"
]
]
The problem was that I thought that writing
return back()->with('bladeVar', $controllerVar) was the same as return view('test')->with('bladeVar', $controllerVar);,but it wasn't .
You cannot echo a variable using blade normal syntax: {{ $bladeVar }}, Instead, you have to access the session to get the value: {{ session('bladeVar') }}.
After I changed the way I displayed the data all worked as expected.
The answer is you can not.
If you want to use with() then use it with view() like:
return view('welcome')->with(['name' => 'test']);
You can not use with() with back() and redirect(). It won't give you any error but you will not get the variable on the view.
More info: https://laravel.com/docs/master/views#passing-data-to-views
return redirect()->back()->with('result',round($area, 2))->withInput($request->all());
call
{{Session::get('result')}}
in your blade.
return view('profile.reset', compact('user'));
I have a form with this fields in laravel:
<form>
<input type='text' name="title">
<input type='file' name="files">
</form>
In server side, I done some proccess on files.
$imagesUrl = $this->uploadImages($request->file('files'));
dd($imagesUrl):
array:2 [▼
"images" => array:4 [▼
"original" => "/upload/images/2017/10453717_202487510125261_45876946_n.jpg"
300 => "/upload/images/2017/300_10453717_202487510125261_45876946_n.jpg"
600 => "/upload/images/2017/600_10453717_202487510125261_45876946_n.jpg"
900 => "/upload/images/2017/900_10453717_202487510125261_45876946_n.jpg"
]
"thumb" => "/upload/images/2017/300_10453717_202487510125261_45876946_n.jpg"
]
Now I want replace $imagesUrl with $request->file('files') and insert new record in database.
I try this:
auth()->user()->article()->create(array_merge($request->all() , [ 'files' => $imagesUrl]));
But I get this error:
(1/1) ErrorException Array to string conversion
what is my wrong?
Answer: I added this code in modal
protected $casts = [
'files' => 'array'
];
You should try this:
$imagesUrl = serialize($imagesUrl);
$arrInsert = ['title'=> $request->title,'files'=>$imagesUrl];
auth()->user()->article()->create($arrInsert);
and retrieve it again and then unserialize
$imagesUrl = unserialize($raw->files);