replace a key value in array with a new value - php

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);

Related

How to validate an array of datetimes in Laravel?

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.

Is there a way to push multiple inputs into the same Db column in laravel?

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

How to validate multiple input in the same (array) laravel

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', 

Laravel 5 search in a JSON file and show data

I have a search engine with typeahead. What I want is that after doing a search and giving the submit, show the results. This gives two problems: first it returns an empty array and second, it does not allow me to access the properties telling me it is not an object.
In controller, I used collect() to allow me to access the properties, but it does not work and WHERE either.
public function store(Request $request)
{
$url = 'storage/json/es/noticia.json';
$datos = file_get_contents($url);
$data = json_decode($datos, true);
$data = collect($data)->where("title","LIKE","%{$request->texto}%")->all();
return view('web.buscar.index', compact('data'));
}
If I use $data = collect($data)->all(); I can see the collection:
array:8 [▼
0 => []
1 => array:4 [▼
"id" => 2
"title" => "There is a title"
"lead" => "There is a lead"
"slug" => "there-is-a-title"
]
2 => array:4 [▶]
3 => array:4 [▶]
4 => array:4 [▶]
5 => array:4 [▶]
6 => array:4 [▶]
7 => array:4 [▶]
]
Then If I try: $value->title in the view I have the error: Trying to get property 'title' of non-object. In the view I have:
{!! Form::open([
'route' => 'buscar',
'id' => 'buscar',
'name' => 'buscar',
'class' => 'buscador col-xs-12',
'method' => 'POST',
'accept-charset' => 'utf-8'
]) !!}
<input id="texto" name="texto" class="input_buscador typetitulo" autocomplete="off" type="text"/>
{!! HTML::image('images/web/icons/lupa.svg', '', array('height' => '30', 'class' => 'boton_buscador', 'onclick' => 'document.buscar.submit()') ) !!}
{!! Form::close() !!}
#if(isset($data))
#foreach($data as $value)
<span>{{$value->title}}</span><br>
#endforeach
#endif
If I use $data = collect($data)->pluck('title'); in the controller and in the view I don't call the property 'title', this works, but it's not what I want because I need to access other properties too.
Any idea? Thanks in advance!
This is failing because the first array in your array does not have any values, so you will get undefined index, remove any empty arrays by doing
public function store(Request $request)
{
$url = 'storage/json/es/noticia.json';
$datos = file_get_contents($url);
$data = json_decode($datos, true);
$data = array_filter($data);
$data = collect($data)->where("title","LIKE","%{$request->texto}%")->all();
return view('web.buscar.index', compact('data'));
}
Or you can test to see if it is there in your foreach
#foreach($data as $value)
<span>{{$value->title ?? ''}}</span><br>
#endforeach
You can then search the collection using a filter
collect($data)->filter(function ($item) use ($request) {
return $item->title == $request->texto;
)
You can edit the return to be more granular using stristr etc

Which Image value need to add to Source field to upload FB photo

I'm trying to upload a photo to facebook via my laravel application. I have some questions.
I uploaded photo and the got image properties with dd($_FILES) and the result is
array:1 [
"file" => array:5 [
"name" => "shailene_woodley_divergent-wide.jpg"
"type" => "image/jpeg"
"tmp_name" => "/private/var/folders/b0/l7j5d8tj2ynflwt8srr5lywm0000gn/T/phpxHoc6s"
"error" => 0
"size" => 573957
]
]
and my controller is
try {
$response = $this->fb->post('/me/photos',
array(
'source' => ?????????,
'caption' => 'nothing',
'published' => 'false'
)
);
Please let me know which value of photo do i need to add in source field.
thanks

Categories