Laravel: Trying to push url strings to array in database - laravel

I have a field in my AppSetup table called reference_images that is added as follows in the migration: $table->json('reference_images')->nullable(); and casted as an array in the AppSetup model. I have a method that adds image urls to the database. If it's for the reference_image field, I am trying to push it to the array but I keep getting an "Array to String conversion" error in Laravel.
public function addImagesToAppSetup($imageType=null, $image=null)
{
$appSetup = AppSetup::where('store', '=', id())->first();
if ($image) {
if ($imageType == "reference_images") {
$originalArray = $appSetup->$imageType;
$originalArray[] = $image;
$appSetup->$imageType = array_values(array_unique($originalArray));
} else {
$appSetup->$imageType = $image;
}
}
$appSetup->save();
return response()->json(['status' => 1, 'data' => $appSetup]);
}

Since reference_images is of type json, doing array_values(array_unique($originalArray)); is still an Array. You will have to convert it to json.
e.g. using collect()->json() docs
$appSetup->$imageType = collect($originalArray)->unique()->values()->toJson();

Related

Laravel Mutator for append url for JSON array

I have a JSON field in my MySQL table column which has an JSON array with part of URLs.
["products/1.jpg", "products/2.jpg", "products/3.jpg"]
I want to get the array with appending a Base URL for each of the values of the array.
["www.example.com/images/products/1.jpg", "www.example.com/images/products/2.jpg", "www.example.com/images/products/3.jpg"]
I have tried with getAttribute() function like nelow code. But was not succeeded.
public function getImagesAttribute(){
$images = json_decode($this->attributes['images']);
$imageP = [];
foreach ($images as $image) {
$imageP[] = "www.example.com/images/" . $image;
}
return $imageP;
}
can you help me.
You probably want to use $this->images instead of $this->attributes['images'].
In this case, I would use Collections like so:
public function getImagesAttribute(){
return collect(json_decode($this->images))
->map(function ($image) {
return "www.example.com/images/" . $image;
})
->all();
}

I can't add string to all value an array

I am new in developing ِAPi from laravel i need to insert path app into value an array
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')->where('halls.id',157)
->get();
$results=[];
foreach ($halls as $hall) {
$array=json_decode($hall->image_path,true);
if (is_array($array))
{
$hall->image_path = 'http://127.0.0.1:8000/Imaga_halls/'.$array;
}
array_push($results, $hall);
}
return response()->json($results);
}
the error is
ErrorException: Array to string conversion
$hall->image_path = 'http://127.0.0.1:8000/Imaga_halls/'.$array;
You are trying to concat an array to a string here.
After get() method on query builder, you will get the collection, so that you can use map() function to loop every hall object.
And concat prefix path with image:
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')
->where('halls.id',157)
->get();
$results = $halls->map(function($hall) {
$array = json_decode($hall->image_path, true);
$hall->image_path = collect($array)->map(function($image) {
return 'http://127.0.0.1:8000/Imaga_halls/'.$image;
})->toArray();
return $hall;
});
return response()->json($results);

Laravel 5.4 Return as array not object

The following method is intended to return an array with another array, 'data' and an Object (The result of some eloquent query).
It is however returning an array with two objects in it; $data is somehow being converted to an object with multiple child-objects, rather than being an array of objects. It should be noted that a dd($data) before the return statement reveals that it is indeed an array of objects. I think that somehow the Laravel middleware that handles response is returning this as an object instead...
Any idea how to work around this?
public function getTestData($id) {
$participants = Participant::where('test_id', $id)->with('testRecords')->get();
$finalRecordValue = TestRecord::where('test_id', $id)->orderBy('created_at', 'desc')->first();
$data = [];
foreach ($participants as $participant) {
foreach ($participant->testRecords as $testRecord) {
if (!array_key_exists((int)$testRecord->capture_timestamp, $data)) {
$data[$testRecord->capture_timestamp] = (object)[
'category' => $testRecord->capture_timestamp,
'value' . "_" . $participant->id => $testRecord->score
];
} else {
$data[$testRecord->capture_timestamp]->{"value" . "_" . $participant->id} = $testRecord->score;
}
}
}
return [$data, Auth::user()->tests()->findOrFail($id)];
}
Try this before excuting return sentence or in it:
array_values($data);

Sending an array to index via Algolia's Laravel Search Framework

I'm having some difficulty sending an array to be indexed in Algolia because I have to encode it to save it to the database first.
$algoliaAgent = AlgoliaAgent::firstOrCreate([
'FirstName' => $item->FirstName,
'LastName' => $item->LastName,
'AgentRecId' => $item->AgentRecId,
'Style' => json_encode(explode(',', $item->Style))
]);
$algoliaAgent->pushToIndex();
The resulting index in Algolia looks like this:
"[\"value1\",\"value2\",\"value3\"]"
Is there a method to decode the value before sending it to Algolia?
I believe you are looking for the json_encode and json_decode methods.
Also, see the Laravel Scout documenation for more information about what is indexed.
By default, the entire toArray form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray method on the model:
The final solution was to modify the pushToIndex() method to intercept the the loop that sends the object to Algolia.
Something like this:
public function pushToIndex()
{
/** #var \AlgoliaSearch\Laravel\ModelHelper $modelHelper */
$modelHelper = App::make('\AlgoliaSearch\Laravel\ModelHelper');
$indices = $modelHelper->getIndices($this);
/** #var \AlgoliaSearch\Index $index */
foreach ($indices as $index) {
if ($modelHelper->indexOnly($this, $index->indexName)) {
$temp = $this->getAlgoliaRecordDefault($index->indexName);
$temp['Style'] = $this->castArray($temp['Style']);
//$index->addObject($this->getAlgoliaRecordDefault($index->indexName));
$index->addObject($temp);
}
}
}
public function castArray($raw) {
$arrayString = '';
if(is_string($raw)) {
$arrayString = explode(",",$raw);
}
return $arrayString;
}

Why I am getting error message when using Yii CActiveForm::validate() with array

I have a problem related to CActiveForm::validate(). I have a form and and sending data to database using Ajax, my form contains a multiple selectable drop-down list. In data saving section of controller produced the following error initially
mb_strlen() expects parameter 1 to be string, array given (.../framework/validators/CStringValidator.php:84)
and after updating framework to newer version, that error gone, and got the below validation message instead.
Category Ids is invalid.
If the form is fully filled(I mean all the rules in the model satisfied), it will not produce any such bug or error message.
controller action
public function actionCompany() {
$model = new Company;
if (isset($_POST['Company'])) {
$model->attributes = $_POST['Company'];
$category_ids = "";
if (is_array($_POST['Company']['category_ids']))
$category_ids = implode(',', $_POST['Company']['category_ids']);
$model->category_ids = $category_ids;
if ($model->validate()) {
/*$temp = Company::model()->findByPK($model->id);
if ($temp !== null) {
$model = $temp;
}*/
$model->save();
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate($model);
if ($error != '[]')
echo $error;
}
}
}
Model rules
public function rules()
{
return array(
array('...., category_ids,...', 'required'),
array('..., category_ids, ...', 'length', 'max'=>255),
....
.....
array('...., category_ids,...', 'safe', 'on'=>'search'),
);
}
What is actually I'm missing?
By default, CActiveForm::validate($model) loads the model attributes from $_POST and overrides current attribute values, thus destroying your transformed values. Pass false as the third argument to avoid this.

Resources