I am using Laravel 5.2 and have a problem.
My code is;
$sts = STSMember::find($member_id)->join('rating', 's_t_s_members.member_id', '=', 'rating.member_id');
But I get the following error
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string'.
How to get member_id from two table?
find returns a model instance, you need either:
STSMember::where("id","=",$member_id)->join('rating', 's_t_s_members.member_id', '=', 'rating.member_id')->get();
Or ideally:
class STSMember extends Model {
//Other model code
public function rating() {
return $this->belongsTo(Rating::class);
}
}
Then you can do:
STMember::with("rating")->find($member_id);
Check https://laravel.com/docs/5.4/eloquent-relationships
Related
I Want To Use Relation Methods In Scopes But It Gives an Error.
Error:
Call to undefined method Illuminate\Database\Eloquent\Builder::members()
Controller:
$members = $book->MembersLoanedCurrentBook()->paginate(8);
Scope:
public function scopeMembersLoanedCurrentBook(Builder $query): Builder
{
return $query->members()->orderBy('return_date')->where('book_member.returned',false);
}
Assuming your models are something akin to User hasMany BookMember and Book has an attribute called returned, you can use Laravel's with` query scope:
Users::with(['member_books', function ($q) => {
$q->returned
})->get();
#geertjanknapen was right that this is a possible duplicate. You can achieve the same result using the methods from this question.
What you are doing is defining a scope and in that scope querying a relationship for a specific property or value.
public function scopeMembersLoanedCurrentBook(Builder $query): Builder
{
return $query->members()
->orderBy('return_date')
->whereHas(['book', function ($q) => {
$q->returned == false;
});
});
}
Without knowing the model structure and relationships, it's hard to write out an exact solution, but something along these lines should work.
You can't work with relations in scope, because your work with Builder $query.
public function scopeMembersLoanedCurrentBook(Builder $query): Builder
{
return $query->orderBy('return_date')
->where('returned',false);
}
And
$members = $book->members()->MembersLoanedCurrentBook()->paginate(8);
Can someone please tell me how can I achieve something in a Laravel Model?
One of the columns contains json_encoded data:
["1", "7", "13", "18"]
I have a model for this specific table and when I'm trying to get the data from different tables based on those ids, it won't work as variable is always null:
use App\Models\VehiculeType;
...
class Freight extends Model
{
...
public function selected_vt() {
return VehiculeType::whereIn('id', json_decode($this->vehicules))
->get();
}
}
Then in the controller:
$freights = Freight::with('selected_vt')
->where('user_id', Auth::user()->id)
->get();
And I'm getting this error:
Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given
I am sure I'm making some fundamental error trying to do this in the completely wrong way.
Unfortunately you can't use with with collection, and selected_vt must return relation instance rather than a collection.
Try eloquent-json-relations package, it can helps you with your situation:
https://github.com/staudenmeir/eloquent-json-relations
Here is an example depending your situation
After installing package
in Freight Modle
class Freight extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
protected $casts = [
'vehicules' => 'json'
];
public function vehicules()
{
return $this->belongsToJson(VehiculeType::class, 'vehicules');
}
}
If you want the reversed relation
in VehiculeType Model
class VehiculeType extends Model
{
use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function freights()
{
return $this->hasManyJson(Freight::class, 'vehicules');
}
}
Then in the controller:
$freights = Freight::with('vehicules')
->where('user_id', Auth::user()->id)
->get();
I created an Eloquent Model :
class VehicleDetails extends Model
{
//
protected $table = 'v_vehicle_details';
protected $primaryKey = 'model_id';
public function tariffs()
{
return $this->hasMany('App\Tariffs', 'vehicle_model_id', 'model_id');
}
}
The table structure for the same is v_vehicle_details is
v_vehicle_details
The table structure for tariffs is
t_tariffs
The Model is being called in controller like :
public function booking_view(){
$vehicle_details = new VehicleDetails();
return $vehicle_details->find(5)->tariffs();
}
What I need is to get vehicle details with all tariffs, But when I try that it throws an error Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string. Can somebody please help, I am new to laravel.
These are not actual tables, But views.
change to
return VehicleDetails::with('tariffs')->find(5);
This is because calling the method ->tarrifs() will return a relationship object in this case HasMany this means you still have to perform the query on this object to get the results.
If you use it as a property ->tarifs without () it will perform the query.
This is the same as tarifs()->get() just a shortcut.
Change your function to:
public function bookingView(){
$vehicle = VehicleDetails::with('tariffs')->find(5);
return view('your.view', compact('vehicle'));
}
The with() will eager load the tariffs relation.
You can acess your tariffs in your view like this:
{{$vehicle->tariffs->anyAttributeYouWantToAccess}}
I am trying to make a one-to-many relationship, but I get the following error
Undefined property: stdClass::$client (View:
C:\wamp\www\intranet\resources\views\users\list.blade.php)
The problem is that I am working with an existing database that in the tables does not have id fields, and the foreign keys would also be the typical ones like client_id
My model Client.php
class Client extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmundfunc';
public function employee(){
return $this->hasMany('App\Employee');
}
}
My model Employee.php
class Employee extends Model
{
protected $connection = 'dpnmwin';
protected $table = 'nmtrabajador';
public function client(){
return $this->belongsTo('App\Client', 'COD_UND');
}
}
In nmtrabajador COD_UND field would be the foreign key that relates to nmundfunc.
And I try to get the data out like this: {{$user->client->CEN_DESCRI}}.
but it does not throw me the error, how can I solve it?
My Controller where I send in sight
public function index(){
$users = DB::connection('dpnmwin')->table('nmtrabajador')->where('CONDICION', '=', 'A')->get();
return view('users.list',array(
'users' => $users
));
}
You have to call basis on relations.
This code will return you data.
If you have id then you can find by id like below
$employee=Employee::find(1);
Or if you want to fetch all data then you can call all method.
Employee::all();
And then you can just get it by relation as you define in models.
$client=$employee->client->CEN_DESCRI;
Retrieving data from the instance is based on the methods which we have use.
Here in this answer, you can get that
Property [title] does not exist on this collection instance
I hope it will work.
If table doesn't have 'id' as primary key you should specify what the primary key is inside your model:
protected $primaryKey = 'your_primary_key';
Relation looks good, after that you must make sure $user is a defined instance of Employee, because your error probably means that your instance wasn't even defined, so for example if you are using list.blade.php, you need to change the return of your controller and indicate that you want to pass data to your view, for example you could do it like this:
return view('users.list', compact('user'));
Where user is an instance of Employee saved on '$user'
Update
First you should check your user is retrieved properly, you can check it by placing a dd($user)
And when you return a view you can pass information to it, a cleaner way of doing what you are trying to do is what I wrote earlier so you would end up having something like this:
public function index()
{
$users = DB::table('nmtrabajador')
->where('CONDICION', '=', 'A')
->get();
// dd($user) for debugging you are retrieving the user properly
return view('users.list', compact($users));
}
I'm trying to fetch database data through a model relationship in Laravel.
I've set up one model, like this:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Userskeywords extends Eloquent {
public function relatedKeywords()
{
return $this->hasOne('Keywords', 'id', 'keywordId');
}
}
?>
And the other model is just a normal model. In the database they look like this:
Keywords
UsersKeywords
However, when I run UsersKeywords::with('relatedKeywords')->get() it returns NULLfor related_keywords. This happens when the following code is executed. What am I doing wrong?
$keywords = Userskeywords::where('user', '=', $id)->get();
$keywords->load('relatedKeywords');
return Response::json($keywords);
Your relation is called relatedKeywords so you need to access related object with
$object->relatedKeywords
instead of
$object->related_keywords