Input array loop on controller laravel 5 - laravel

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

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

how to use $request->all() on controller and blade view in laravel 5.5

in Controller
public function index(Request $request)
{
$search_cons = $request->all();
$search_con = $search_cons->name; //error place
return $search_cons.$search_con;
}
->name this place has the error
Trying to get property of non-object
Or in blade.view
<p>{{$search_cons->name}}</p> has the error
Trying to get property of non-object
But if I use
$search_cons=$request->input('name');
on controller
the blade view
<p>{{$search_cons}}</p> will work ok!
I want the $search=request->all() so I can freely use $search->name on my blade view
How can I fix the question?
PS: I tried $resquest('name') still not to work
Request::all() ->tell me the
When you do $request->all() it returns all the inputs submitted in array format. So in your case, you can do
$search_cons = $request->all(); // dd($search_cons) so you can see its structure
$search_con = $search_cons['name']; // instead of ->name since it's not an object anymore
And anyway, you can skip the $request->all() thing - you can actually just do this directly:
$request->name.
EDIT:
You can cast the array as an object using (object)
$search_cons = (object) $request->all();
this will still let you use $search_cons->name
$search_cons is an array, not an object:
$search_con = $search_cons['name']
public function index(Request $request)
{
$search_cons = $request->all(); //returns array
$search_con = $search_cons['name']; //error place
return $search_cons.$search_con;
}
Or you can do like this
request()->name //request() isa global helper function
Try
In Controller
public function index(Request $request)
{
$search = $request->all();
return ['search' => $search];
}
In Blade
<p>Name : {{$search['name'] ? $search['name'] : ''}} </p>

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

Laravel and algolia, ignore array if null

I have this code:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
return $data;
}
However sometimes $data['entities'] is null therefore throwing me an error:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to a member function toArray() on null
Is there any way to by-pass that?
You need to check elements if they exist and not null before call methods on them, like this:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = !empty($this->_geoloc) ? $this->_geoloc->toArray() : null;
$data['address'] = !empty($this->address) ? $this->address->toArray() : '';
return $data;
}
Also $this->toArray(); will convert the model instance to an array with all relations. So you need to load them like: $this->load('_geoloc', 'address'); and call only $data = $this->toArray();
I assume address is a relation to another table.
toArray() will convert it, if it was loaded before
public function toSearchableArray()
{
$this->address;
$data = $this->toArray();
return $data;
}
Is _geoloc also a relation to another table?
I think you can try this:
public function toSearchableArray()
{
$data = $this->toArray();
$data['_geoloc'] = $this->_geoloc->toArray();
$data['address'] = $this->address->toArray();
print('<pre style="color:red;">');
print_r($data);
print('</pre>');
exit;
return $data;
}
Hope help for you !!!

Handling non objects

I might have a controller function like so
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
This is fine if the three collections I am obtaining contain data. If they dont and I try to visit the index page, I get
ErrorException in PollResponseController.php line 20: Trying to get property of non-object
So what is the best way to handle non-object's? To bypass this, I could do
public function index()
{
$poll = DB::table('poll')->whereNull('deleted_at')->orderBy('id', 'desc')->first();
if($poll) {
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
if($question) {
$answers = DB::table('poll_answer')->whereNull('deleted_at')->where('question_id', $question->id)->orderBy('id')->get();
return view('index', compact('poll', 'question', 'answers'));
}
}
return view('error');
}
But is that not a bit exessive? I was just wondering if there was a better approach to handling this?
Thanks
You can use simple if($question) clause or if(is_null($question)).
$question = DB::table('poll_question')->whereNull('deleted_at')->where('poll_id', $poll->id)->first();
if($question){
// The object is not empty, so I'll use it
}else{
// The object is empty
}
In a blade template it will look like #if($question) and #if(is_null($question)) respectively.
#if($question)
{{ $question->property }}
#endif
In most cases you should just bypass all variables in a template and then check each of them with #if clauses.

Resources