Laravel and algolia, ignore array if null - laravel

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

Related

Post with xml file in laravel

I am using method post to create new data in xml file but The function c_element cannot be used in the function store
$DeTai = c_element('DeTai', $root);
This is my current code:
public function c_element($e_name, $parent)
{
global $xml;
$node = $xml->createElement($e_name);
$parent->appendChild($node);
return $node;
}
public function c_value($value, $parent)
{
global $xml;
$value = $xml->createTextNode($value);
$parent->appendChild($value);
return $value;
}
public function store(Request $request)
{
$xml = new DOMDocument("1.0","UTF-8");
$xml->load('../xml/QuanLyDoAnTotNghiep.xml');
if ($request->isMethod('post'))
{
$madt= $request->madt;
$noidungdetai = $request->noidungdetai;
$root=$xml->getElementsByTagName("QuanLyDoAnTotNghiep")->item(0);
$DeTai = c_element("DeTai", $root); //error in here
$s_madt = c_element('MaDT', $DeTai);
c_value("$madt", $s_madt);
$s_noidungdetai = c_element('NoiDungDeTai', $DeTai);
c_value("$noidungdetai", $s_noidungdetai);
$xml->formatOutput=true;
$xml->save('../xml/QuanLyDoAnTotNghiep.xml');
echo "Thêm mới thành công!!!";
}
}
use this keyword to call one method in different method of same class
$DeTai = $this->c_element('DeTai', $root);
to know more about it please visit this
Thanks..

Argument 2 passed to Spatie\Searchable\SearchResult::__construct() must be of the type string, null given

im using spatie/laravel-searchable for my website.
it works very well in this function:
public function index(Request $request)
{
$results = (new Search())
->registerModel(Product::class, 'name', 'price','barcode')
->registerModel(Category::class, 'name')
->registerModel(Catalog::class, 'name')
->registerModel(Color::class, 'fatitle','entitle')
->search($request->input('query'));
return response()->json($results);
}
but in some words(like:cu006), i have this error:
Argument 2 passed to Spatie\Searchable\SearchResult::__construct() must be of the type string, null given
vendor/spatie/laravel-searchable/src/SearchResult.php:19
public function __construct(Searchable $searchable, string $title, ?string $url = null)
In your model, when you create the getSearchResult function
public function getSearchResult(): SearchResult
{
return new \Spatie\Searchable\SearchResult(
$this,
$this->title
);
}
If you write $this->title you need to make sure that your model actually contains the title field, if it doesn't it'll give you that error.
public function getSearchResult(): SearchResult
{
$companySlug = currentCompanySlug();
$url = url('/'.$companySlug.'/'.config('global-search- url.'.class_basename($this)));
$null = null;
return new SearchResult($this, $this->field_name ?:$null, $url);
}
please add in your model.

Calling a method inside another method and passing a parameter in a controller

The first method has a condition of the query and it returns the count of the query specified.The 2nd method calls the 1st method. First question, how can i pass the parameter $compid to Method countEmployee from Method userSummary? Second question, Is this the right thing to call method countEmployee inside method userSummary?
1st Method
public function countEmployee($compid){
$query = User::query();
$company = $query;
// $thgarments = $query;
$company->whereHas('company', function ($q) {
$q->where('company_id','=', $compid);
});
$company->where('emp_status','=', 'Regular');
$totalemployee = $company->count();
return $totalemployee;
}
2nd Method
public function userSummary()
{
$tenghwa = countEmployee(2);
}
Try this corrected code
public function countEmployee($compid)
{
$query = User::query();
$totalemployee = $query->whereHas('company', function ($q) use ($compid) {
$q->where('company_id','=', $compid);
})->where('emp_status','=', 'Regular')
->count();
return $totalemployee;
}
public function countEmployee($compid){
$query = User::query();
$company = $query;
// $thgarments = $query;
$company->whereHas('company', function ($q) use($compid) {
$q->where('company_id','=', $compid);
});
$company->where('emp_status','=', 'Regular');
$totalemployee = $company->count();
return $totalemployee;
}
public function userSummary()
{
$tenghwa = $this->countEmployee(2);
}
I realized my mistake. I should "use" $compid in the first method, and in the second method i should put a $this to calling the countEmployee method.

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

Setting a table name in a model?

Im trying to pass in a table name to my model, as the model operates on two tables, but has the same methods.
I do it like so:
$this->model = new Emotions(array('section' => 'red'));
And in the model I set the table like:
public function __construct($attributes = array(), $exists = false){
parent::__construct($attributes, $exists);
$this->table = $attributes['section'];
}
But I get the error:
Undefined index: section
Any ideas where I'm going wrong?
Yes i get it, This class maybe running twice.
Please try this.
public function __construct($attributes = array(), $exists = false){
parent::__construct($attributes, $exists);
if(isset($attributes['section'])) {
$this->table = $attributes['section'];
}
}
My personal suggestion
<?php
class Emotions extends Eloquent
{
public function setTableName($name)
{
$this->table = $name;
return $this;
}
}
And you can use like this
$emotion = new Emotions(array('foo' => 'bar'))
->setTableName('blabla')
->save();
add below line to your class.
protected $fillable = array('section');
http://laravel.com/docs/eloquent#mass-assignment

Resources