Laravel Mutator for append url for JSON array - laravel

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

Related

I can't edit the ids in a map of a Laravel collection

Hello everyone I have this problem with the Models and Map in Laravel:
I have a code that is more or less like this:
public function getProducts()
{
$products = Product::selectRaw('
products.id,
products.name
');
return $products->paginate(15);
}
public function parseProducts()
{
$data = $this->getProducts();
$data->map(function ($item) {
$item->id = $this->encrypt($item->id);
return $item;
});
return $data;
}
The encryption code works fine but in this loop it doesn't, it returns all ids with 0.
If I use DB::table("products") instead of Product everything works fine.
Will there be any blockage?

Laravel query to output json data as select list. How to amend existing code to concatenate two values

I've got a pre-existing function in my controller that will run a simple query and return the model_name and id then return the result as json.
public function getModel($id)
{
$models = DB::table('model')->where('man_id',$id)->pluck('model_name','id');
return json_encode($models);
}
New requirement is that I include an additional column named model_num with the query. Plan is to concatenate the model_name and model_num columns.
Tried the following, but it doesn't return any values and I get a 404 response for the json:
public function getModel($id)
{
$models = DB::table("model")->select("id","CONCAT(model_name, '-', model_num) as model")->where("man_id",$id)->pluck('model','id');
return json_encode($models);
}
Am I missing something obvious?
You are using SQL functions within a select these will probably not work. You can use selectRaw instead:
public function getModel($id)
{
$models = DB::table("model")
->selectRaw("id, CONCAT(model_name, '-', model_num) as model")
->where("man_id",$id)
->pluck('model','id');
return response()->json($models); // response()->json() is preferable
}
alternatively you can do the concatenating in the PHP side:
public function getModel($id)
{
$models = DB::table("model")
->select("id", "model_name" "model_num")
->where("man_id",$id)
->get()
->mapWithKeys(function ($model) {
return [ $model->id => $model->model_name.'-'.$model->model_num ];
})
return response()->json($models);
}
public function getModel($id)
{
$models = DB::table('model')->where('man_id',$id)->first() ;
$models->model = $models->model_name. '-'. $models->model_num;
return json_encode($models->pluck('model', 'id');
}

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

Input array loop on controller laravel 5

I have inputs array and i need to make a foreach but laravel $request->all() only return last one:
url:
http://localhost:8000/api/ofertas?filter_pais=1&filter_pais=2&filter_pais=3
controller:
public function filtroOfertas(Request $request){
return $request->all();
}
result:
{"filter_pais":"3"}
result should return 1, 2 and 3 and i need to make a foreach in filter_pais.
Any solution? Thanks
Use [] at the key of query string.
http://localhost:8000/api/ofertas?filter_pais[]=1&filter_pais[]=2&filter_pais[]=3
It will be parsed as array.
Repeated parameters make no sense and should be avoided without exception.
But looking at other solutions, there are several:
routes.php
Route::get('/api/ofertas/{r}', 'Controller#index');
Controller:
public function index($r)
{
$query = explode('&', $r);
$params = array();
foreach($query as $param)
{
list($name, $value) = explode('=', $param);
$params[urldecode($name)][] = urldecode($value);
}
// $params contains all parameters
}
Given that the URL has no question marks:
http://localhost:8000/api/ofertas/filter_pais=1&filter_pais=2&filter_pais=3

How to pass a view and a json from a function in laravel?

This is my function
if(isset($_POST['franchisesIds'])) {
$id_array = array();
foreach($_POST['franchisesIds'] as $data) {
array_push($id_array, (int)$data['id']);
}
$results = DB::table('franchises')->whereIn('id', $id_array)->get();
}
return Response::json(array($id_array));
return View::make('frontend.stores')->with('franchisesAll', $results);
So I am a little bit confused on how to pass all this data. I need to pass the json just to make sure everything worked. And at the same time I need to pass a list of ids to the view.
How can I do this??
Hopefully this is what you wanted :
Please don't use directly $_POST or $_GET instead use Input
$franchisesIds = Input::get('franchisesIds');
$id_array = array();
if($franchisesIds) {
foreach( $franchisesIds as $data) {
array_push($id_array, (int)$data['id']);
}
$results = DB::table('franchises')->whereIn('id', $id_array)->get();
}
$jsonArray = json_encode($id_array);
return View::make('frontend.stores')->with(array('franchisesAll'=>$results,'idArrays'=>$jsonArray));
In order to pass multiple values to the view, please read more about it in the official Laravel documentation
First of all you should use Input::get('franchisesIds') instead of $_POST['franchisesIds'], also there is no reason to do this foreach loop:
foreach($_POST['franchisesIds'] as $data) {
array_push($id_array, (int)$data['id']);
}
Because this is already an array and you are bulding another array from this array, makes no sense. So you may try this instead:
if($franchisesIds = Input::get('franchisesIds')) {
$franchises = DB::table('franchises')->whereIn('id', $franchisesIds)->get();
}
Then to pass both $franchisesIds and result to your view you may use this:
return View::make('frontend.stores')
->with('franchises', $franchises)
->with('franchisesIds', $franchisesIds);
You can also use something like this (compact):
return View::make('frontend.stores', compact('franchises', 'franchisesIds'));
There is no reason to use json_encode to encode your $franchisesIds.
You could also use
$results = DB::table('franchises')
->whereIn('id', $id_array)
->get()
->toJson();

Resources