Why do Laravel relationships prevent calls to query builder methods? - php

I want to find all patients that belong to a user where id = 1
This works:
$data = Patient::where('user_id', '=', 1)
->with('method', 'images')->get()->toJson();
This doesn't work:
$data = User::find(1)->patients->with('method', 'images')->get()->toJson();
It says:
Call to undefined method Illuminate\Database\Eloquent\Collection::with()
Why is it wrong? Could it be corrected?

The reason your code doesn't work is all Eloquent relationship declaration returns different result depending on whether you are trying to access the relationship as property or as method (with () or without ()).
// Return you chainable queries
$query = User::find(1)->patients()->...
// Return you collection of patients
$patientsCollection = User::find(1)->patients;

Try
User::find(1)->patients()->with('method', 'images')->get()->toJson();

Try this
$patient = New Patient;
$data = $patient->where('user_id','=',1)->with('method','images')->get()->toJson();

Related

Too few arguments for view error with laravel

I'm having a problem with laravel., I'm trying to send the variable $codes on my view :
$codes = Code::where('user', $id)->get();
return view('user.edit', ['user' => $user,'codes' => $codes]);
But I get that error Too few arguments to function e(), 0 passed in
The variable $user goes well but not the variable code, anyone have an idea for a solution?
Thank you all
use this:-
return view('user.edit')->with('codes',$codes);
you can get the user with :-
Auth::user()->name;
I'm pretty sure, if you are following Laravel naming conventions, in your eloquent query the column name is user_id and not user. Also if you are using such querys, and you have foreign, you can define relations in your models, like the following:
Code Model
public function user
{
$this->belongsTo(User::class);
}
User Model
public function codes
{
$this->hasMany(Code::class);
}
Instead of line
$codes = Code::where('user', $id)->get();
You can go with:
$codes = $user->codes();
If you don't have the foreigns in your database
$codes = Code::where('user_id', $id)->get();
If non of these helps, please dd() your variables before returning the view, and share result with me in comment. In laravel 7 how you return view is good.

Data comparison in laravel

I'm beginner in laravel and I'm trying to run comparison queries given in the database.
I saved a field date that is implemented by a form together with other fields including the name.
I tried to query the name and it works all regularly with this code below.
I would like to retrieve all the rows that have the name variable as the field name that I pass (and here it seems to work) and then only those with the field date that have the specified month at the number that I pass as variable $month.
what would be the right form to do this?
thanks
Piero
public function filterparamenter(){
$name = request('name');
$month = request('$month');
$query = subagente::all();
$query = $query->where('subagente', $subagente);
$query = $query->whereMonth('data', $month)->get();
Method Illuminate\Database\Eloquent\Collection::whereMonth does not exist.
Using ::all() returns a Collection, which has a ->where() method, but ->whereMonth() is only available on Eloquent's Builder class. Change your code as follows:
$query = subagente::query();
$query = $query->where('subagente', $subagente);
$query = $query->whereMonth('data', $month)->get();
Or, more compact:
$results = subagente::where("subagente", $subagente)
->whereMonth("data", $month)
-get();
Using ::query() or ::where() to start your query will generate a Builder instance, which you can chain addition clauses (->where(), ->whereMonth(), etc) on before calling ->get() to return a Collection of subagente records.
Side note, should "data" be "date"?

Call to undefined method CI_DB_mysqli_driver::and()

$q_cat_beauty = $this->db->select('*')->from('ms_categories')->where('source_id', 1)->and('category_name', 'Oral Care')->get();
i am trying to fetch the category name from my table.
There is no and keyword or method in CI. If you want where with and condition you again have to write where
$q_cat_beauty = $this->db->select('*')->from('ms_categories')
->where('source_id', 1)->where('category_name', 'Oral Care')->get();
or use array in where
$q_cat_beauty = $this->db->select('*')->from('ms_categories')
->where(array('source_id'=> 1,'category_name' => 'Oral Care'))->get();
Try This
$q_cat_beauty =
$this->db->where('source_id', 1)
->where('category_name', 'Oral Care')
->get('ms_categories')
->result_array();
The Query builder class dosnt support and() so if you chain 2 where together like above it will represent the and you can keep chaining
https://www.codeigniter.com/userguide3/database/query_builder.html

Only query "Where" if there is a value in Laravel eloquent

I have a search query that needs to be done. However, a search doesn't always have all values set, like in this case.
$aEvents = DB::table('events')
->where('client_id', '=', $client_id);
The question is, how can I make this where statement depend on the value of $client_id. So if the value is empty I don't want the Where statement to occur.
Also, I do not want to write several complete queries with if statements in PHP. To many variables. Ideally I'd like something like this:
$aEvents = DB::table('events')
->(($client_id != "") ? where('client_id', '=', $client_id) : "");
Using eloquent is (really!) nice and save, but I'm not yet up to speed with if statements in std Class objects I guess. Any help is appreciated.
You may try something like this:
$query = DB::table('events');
if(!empty($client_id)) {
$query->where('client_id', $client_id);
}
$aEvents = $query->get(); // Call this at last to get the result
If you are passing client_id to the server via a form/query string(user input) then you may try something like this:
if($client_id = Input::get('client_id')) {
$query->where('client_id', $client_id);
}
Update: For pagination try this:
$aEvents = $query->paginate(10); // For 10 per page
So you may call links() method in your view if you pass it like this:
return View::make('viewName')->with('aEvents', $aEvents);
In the view for pagination links:
$aEvents->links()
You can also use query scopes in the model for this purpose. Scopes allow you to easily re-use query logic in your models. In the model Event, you can add the following query scope:
public function scopeClientID($query, $client_id)
{
if ($client_id != '') {
return $query->where('client_id', '=', $client_id);
} else {
return $query;
}
}
Then from your controller or wherever you're calling it from, you can do the following:
$aEvents = Event::clientID($client_id);
If you want to get all the results, then you can do:
$aEvents = Event::clientID($client_id)->get();
Or if you want pagination, you can do:
$aEvents = Event::clientID($client_id)->paginate();
You can also chain it with other methods like you'd do in a eloquent query.
You can read more about model query scopes at http://laravel.com/docs/eloquent#query-scopes

Can get relatinship only when using find() , can't where using where()

I've some problem i can't understand:
I have many-to-many relationship model, if i use ::find(x) it's working alright, but if i use ::where() i get
Undefined property: Illuminate\Database\Eloquent\Collection::$dlists
Here's my code:
$employee = Employee::whereUsername('xyz')->get();
$lists = $employee->dlists;
returns the error.
$employee = Employee::find(1);
$lists = $employee->dlists;
returns the needed output.
what am i mising?
It's because the query returns a Eloquent Collection, if the usernames are unique you can call whereUsername('xyz')->first() then you get an Employee Object where you will have access to dlists.

Categories