Return multiple values in laravel - laravel

I'm just new in laravel. I want to know. how to return multiple data/value.
public function readItems() {
$data1 = Data1::all ();
$data = Data::all ();
return $data;
}
I'm quite confuse how to do it. I don't to return it as a view, i just want to return only the data. i hope someone could help. thanks a lot..

You could return an array like :
return [data1, $data];
In the other side read it like :
$response = readItems();
$data1 = $response[0];
$data = $response[1];

You can send data to view as like below :
return view('index', ['Data_One'=>$data, 'Data_Two'=>$data1]);

Related

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 !!!

Laravel 5.4 Collection Map Return Values

I'm having trouble creating a function on collection map with return values.
public function getCollectionFakeId($collection, $fieldNames){
$optimus = $this->optimus;
$result = $collection->map(function($item, $key) use ($optimus, $fieldNames) {
return [
$fieldNames[0] =>$optimus->encode($item->id),
$fieldNames[1] => $item->lastname
];
}) ;
dd($result);
return json_decode(json_encode($result), FALSE);
}
As you can see the return fieldNames[0] is being hardcoded. I don't know how many fieldNames it will received. I need to return those fieldnames with obfuscated Id. So basically The only changed is the Id. Here is the screenshot.
As you can see the fieldNames are just 2 but what if it becomes 5 or 6. I don't really know how many fieldNames they are going to pass in the parameter. How can I return it. Thanks.
In case someone will encounter this problem. Here is my solution...
public function getCollectionFakeId($collection, $fieldNames){
$optimus = $this->optimus;
$result = $collection->map(function($item, $key) use ($optimus, $fieldNames) {
$mapFieldNames = array_map(function($v) use ($optimus, $item) {
if( $v == 'id'){
return $optimus->encode($item->id);
}
else{
return $v;
}
}, $fieldNames);
return $mapFieldNames;
}) ;
dd($result);
return json_decode(json_encode($result), FALSE);
}
The result is the same. AWESOME!

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

Why redirect show blank page in model laravel?

I'd like to ask why the following code works, redirects normally, and data is successfully inserted :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
if($category->saveCategory($data)){
return Redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return Redirect::route('admin_posts_categories')->withError('Failed to add category. #ErrorCode : 13');
}
}
Term model :
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return true;
}else{
return false;
}
}else{
return "#Error Code : 4";
}
}
Where as the following only inserts the data but then shows a blank page and doesn't redirect :
CategoriesController :
public function store()
{
$data = Input::all();
$category = new Term;
$category->saveCategory($data);
}
Term Model
public function saveCategory($data){
$this->name = $data['name'];
$this->slug = $data['slug'];
if($this->save()){
$category_taxo = new TermTaxonomy;
$category_taxo->term_id = $this->lastCategoryId();
$category_taxo->taxonomy = 'category';
$category_taxo->description = $data['description'];
if($category_taxo->save()){
return redirect::route('admin_posts_categories')->withSuccess('Category successfully added.');
}else{
return redirect::route('admin_posts_categories')->withError('Failed to add category.');
}
}else{
return redirect::route('admin_posts_categories')->withError('#Error Code : 4.');
}
}
Moreover, I'd like to ask a few related questions, does my code conform to correct design patterns, and where should I put the redirect, in the model or in the controller ?
Try this for redirect:
1. return Redirect::back()->withSuccess('Category successfully added.');
OR
2. return Redirect::to(URL::to('admin_posts_categories'))->withSuccess('Category successfully added.');
Add your redirect login inside Controller. Even if you want to put in model (which is not recommended) use Ardent Hook function i.e. afterSave().
First of all never put redirect logic in model. Models are for putting business logic. Second thing check whether you have created route for admin_posts_categories in route.php or not and how you are calling views. If possible post your route code in question.
I recommend not putting redirects in your model. So the first solution would be the best of the two you have.
But back to your problem. It is showing a blank page because your store function is not returning anything. return $category->saveCategory($data); but as previously stated this method is not best practise.
An excellent tip would be to have a look at Laracasts, this will teach you everything you knew, didn't know and more about Laravel.

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