where Has Condition on a hasMany relationship in Laravel 5.8 - eloquent

I have a relationship in a model FeeModuleModel as shown below
public function heads()
{
return $this->hasMany('App\Models\FeeHeadModel','location_id','id');
}
and in my controller file i need to fetch only the values FeeModuleModel where the FeeHeadModel has type as unstructured
My controller code is as shown below
$modules = FeeModuleModel::where('vt_ay_id', '=', Session::get('sess_ay_id'))->with(['heads'=>function($q){
$q->where('type','=','unstructured');
}])->orderby('priority', 'asc')->get();
This fails with the following error
Call to a member function getRelationExistenceQuery() on array
What is the problem with my code and what I can do to solve it

Please change your code to this one
$modules = FeeModuleModel::with(['heads'=>function($q){
$q->where('type','=','unstructured');
}])->where('vt_ay_id', '=', Session::get('sess_ay_id'))->orderby('priority', 'asc')->get();

Related

Laravel Eloquent - How to manually append accessor/attribute to result

I have an accessor/attribute ( public function getGalleryAttribute() ) that adds an array of images to the model
I used to eager load this with: protected $appends = ['gallery'] , but I got rid of it to be able to control when I want to append the gallery or not.
I can append the gallery to a single model:
$event = Event::find(126)->append('gallery');
But how do I manually append an accessor when there is more than one result?
This doesn't work:
$events = Event::all()->append('gallery');
return $events;
error:
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::append does not exist
If you are using Eloquent 5.5 or later, you can use Collection::each to append to each item:
$events = Event::all()->each->append('gallery');
You should also look into Eloquent: API Resources to define alternative serialization options for the same model.

Eloquent - load accessor along with model data

My model was eager loading a lot of things with accessors. I want to change it to specify accessors in each case. How do I include such accessors with the query, so that I get the basic model data plus the accessor data
Accessors would previously be eager loaded with:
protected $appends = [
'status',
]
But if I get rid of eager loading, and I want to include this acccessor:
public function getStatusAttribute() {
return self::STATUS_ACTIVE;
}
Then I can do this according to the documentation:
$prod = \App\Product::find(736)->status;
That works but I don't get the basic model data.
I can't do: return $prod = \App\Product::find(736)->with('status')->first()
It gives error: Call to undefined relationship [status] on model
So how do I add such accessors to be included with the model data?
Edit:
As Staudenmeir commented, i can do \App\Product::find(736)->append('status');
That solves it for single results. But how do I append data for many results?
Neither append or appends work:
This: \App\Product::whereIn([34, 55])->appends('status');
results in "Method appends does not exist.",
I saw that you can use "appends" on "->paginate()"
$products = \App\Product::whereIn([34, 55])
->paginate(12)
->appends('status');
But that appends it as a query string to the url. Very strange - I want to append it in the same way as for a single result in the json response.
You have not fetched the collection first, and then access the attribute of result.
$prod = \App\Product::find(736);
$status = $prod->status;

How to Pass multiple data array to view Codeigniter

I am new to Codeigniter and have two small question
1: How can I pass two table data array to view?
$data['customers']=$this->customer_model->get_all_customers();
//$products['product']=$this->customer_model->get_all_categories();
//$this->load->view("customer_view",$data);
$product['cats']=$this->customer_model->get_all_categories();
$this->loadViews("customer_view", $this->global, $data, $product);
But I am getting error
2: I am joining two tables to get two tables data but I am getting only one table data?
public function get_all_categories()
{
/*// Get Data from Two tables
$this->db->select('*');
$this->db->from('category');
$this->db->join('customers','customers.categoryID=category.categoryID','Inner');
$query=$this->db->get();
please help me to resolve.
This :
$query=$this->db->get();
Should be :
$query=$this->db->get()->result_array();
Here is solution for Passing multi variable to view
Controller
$data['customers']=$this->customer_model->get_all_customers();
$data['cats']=$this->customer_model->get_all_categories();
$data ['customers'] = $customers;
$data ['cats'] = $categories;
$this->loadViews("customer_view", $this->global, $data);
In view we will use $customers and $categories

Laravel: BadMethodCallException with message 'Method update does not exist.'

When I try to update a model with this code:
public function updateMixedtape($slug, Request $request)
{
$mix = Mix::where('slug', $slug)->get();
$mix->update($request->all());
return redirect('dashboard/mixes');
}
I get an error that method update doesn't exist. However if I modify my view to send a radio_show_id instead of slug and try to change the code to something like this:
public function updateMixedtape(Request $request)
{
$mix = Mix::findOrFail($request->radio_show_id);
$mix->update($request->all());
return redirect('dashboard/mixes');
}
The code executes without any errors.
What puzzles me is that if I do something like return $mix; before the line where I call the update method, I get similar data for both methods.
As shock_gone_wild has suggested in the comment section of my question $mix = Mix::where('slug', $slug)->get(); is returning a collection and not a model. This is because a Model::where() method can return zero, one or many records depending on whether or not there are records that meet the set condition.
As suggested I used $mix = Mix::where('slug', $slug)->first(); instead to get the first record that meets the condition.

How to get Model Object using its name from a variable in Laravel 5?

I am trying to get information from a model using its name which is sent as parameter from blade using ajax call.
$.get("{{ url('auditInformation')}}", {modelName: modelName,versions:versions,currentData:currentData[index]});
Now i need to retrieve information using modelName from a model.
So when i tried this:
$auditInfo=Input::all();
$modelName=$auditInfo['modelName'];
$values=$modelName::find(1);
I got this response Class 'Designation' not found
But if i use
$modelName=new Designation();
$values=$modelName::find(1);
then it shows data exactly what i want.
So i understand that this is all about model ( class ) object.
Is there any way to assign object to $modelName using $auditInfo['modelName'] .
Thanks
If you want to do that way, you should use the model's namespace.
For example, if the 'Destination' model's namespace is app\Destination, you should use like this :
$auditInfo=Input::all();
$appPrefix = 'app';
$modelName=$appPrefix . '\' . $auditInfo['modelName'];
$values=$modelName::find(1);
This seems to be working
$table_name = "App\Models\PeopleYouMayLikeModel";
$obj = $table_name::where($column_name_identifier_1, '=', $row_identifier_1)
->where($column_name_identifier_2, '=', $row_identifier_2)->first();
The single backslash between the singe quote is considered as an escape sequence so use double backslash is 100% work. For example
public function index(Request $request) {
$model_prefix="App\Models";
$modal = $model_prefix.'\\'.$request->type;
$modal::updateOrcreate(['users_id'=>session("user")->users_id],$request->all())->save();
dd(Profile::all());
}
//Laravel 7.0