Laravel relationship `whereNotIn` other table - laravel

I am trying to return all Posts(Model:Post) which have no row in the PostsHistory Model.
My code is:
public function posts(){
return $this->hasMany('App\Post');
}
public function remaining_posts(){
$history = PostHistory::all()->pluck('id');
return $this->posts->whereNotIn('post_id', $history);
}
But I get an error
[BadMethodCallException]
Method whereNotIn does not exist.
Is there any way I could get the remaining_posts through a relationship or can only be done in the controller?

Edit your last line to:
return $this->posts()->whereNotIn('post_id', $history)->get();
i.e.
You need to change posts to posts(). posts is a Illuminate\Database\Eloquent\Collection object which does not have whereNotIn() method where as posts() will return a Illuminate\Database\Eloquent\Relations\HasMany object which has whereNotIn() method defined.
whereNotIn() returns a Illuminate\Database\Query\Builder object. So you need to call get() to get a collection. But if you want the flexibilty to chain other Builder methods to your remaining_posts() method, do not use get().

Related

How can I make pagination of a findorfail method in laravel

I have this function in my controller which is the output of many animals and I would like to paginate it. How am I to do that
controller
public function show($id)
{
$farms = User::with(['animals'])->findOrFail($id);
return view('slaughter.show',compact('farms'));
}
Is there any other way of doing that because I have tried to add the paginate method at the end and I am getting an error
paginate() is a method on the Query Builder instance while findOrFail() returns an Eloquent model, and in this case a single instance, as it is for a single user by the given $id.
You can maybe query the animals through their own model, and paginate it, like this:
public function show($id)
{
$farms = Animal::where('user_id', $id)->paginate(10);
return view('slaughter.show',compact('farms'));
}
I would do this to get a paginated collection of animals for the User. Dependency Injection in the show method as well assuming you also require some user data on the slaughter page.
public function show(User $user)
{
$farms = Animals::where('user_id', $user->id)->paginate();
return view('slaughter.show',compact('farms', 'user'));
}
Your route will need updating, something like this...
Route::get('animals/{user}', 'AnimalsController#show')

Error when using Laravel 5.4 Seeder Function

Type error: Argument 1 passed to
Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an
instance of Illuminate\Database\Eloquent\Model, instance of
Illuminate\Database\Eloquent\Collection given
I am planning to generate Fake date for user with profile. I have two model: User & Profile. I have done the relationship with each others. But when i execute it and the problems came. Above is the error when i running Seeder.
This is the class that found bug.
public function run()
{
factory(App\User::class, 40)->create()->each(
function($user) {
$user->profile()->save(
factory(App\Profile::class, 1)->make()
);
}
);
}
I guess you are using Laravel 5.4.
The has been a modification in the factory() helper method. From the docs:
The factory Helper
Calling factory(User::class, 1)->make() or factory(User::class, 1)->create() will now return a collection with one item. Previously, this would return a single model. This method will only return a single model if the amount is not supplied.
Laravel 5.3 to 5.4 updgrade guide
That means that you should remove the 1 from your factory() call.
public function run(){
factory(App\User::class, 40)->create()->each(
function($user) {
$user->profile()->save(
factory(App\Profile::class)->make()
);
}
);}
Edit 1: You have to change this line:
factory(App\Profile::class, 1)->make()
To this
factory(App\Profile::class)->make()
Getting the relation $user->profile() by calling the method, will return the related models as a Collection. You can do $user->profile()->first() to get a single result of type Illuminate\Database\Eloquent\Model or just $user->profile without the ().

hasOne relationship and associate()?

I have this relationship :
public function company(){
return $this->hasOne('App\Models\User','personal_users_business_users', 'user_id', 'business_user_id');
}
When i try this:
$user->company()->associate($business_user_id);
Im getting this error:
Call to undefined method
Illuminate\Database\Query\Builder::associate()
I have pivot table personal_users_business_users and it has user_id, business_user_id, approved
And now i want to insert in that pivot table business_user_id. What im doing wrong?
Your relationship should be like this:
public function company()
{
return $this->hasOne(User::class);
}
User is the model you want to connect with,
and you should call the relationship like this:
$user->company->business_user_id;
$user must be the Model you have the relationship function in.
company is the function and the business_user_id the field you want to get
associate() is a method of the belongsTo relationship, but it looks like from the above you are trying to call it via the hasOne relationship.
UPDATE
You can create a function in your App\Models\User class
public function company() {
return $this->belongsTo('MODEL_OF_COMPANY', 'foreign_key', 'owner_key', 'relation');
}
then call $this->company()->associate($company)

Laravel 5.2 How to delete parent record from belongsTo relationship?

My Pricing model
protected $fillable = [
'zone_id',
'is_short_time',
'is_service_feeder',
'route_id',
'value',
];
public function route()
{
return $this->belongsTo(Route::class);
}
My Route Model
protected $fillable = [
'zone_id',
'from_city_id',
'to_city_id',
'is_in_the_city',
];
public function pricing(){
return $this->hasOne(Pricing::class);
}
Here is my controller
public function feeder_destroy($zoneid, $pricingfeederid)
{
$pricing_feeder = Pricing::find($pricingfeederid)->where('zone_id', $zoneid)->where('is_service_feeder', 1);
$pricing_feeder->route()->delete();
$pricing_feeder->delete();
}
The error says
Call to undefined method Illuminate\Database\Query\Builder::route()
I want to delete pricing record and route record too.
What wrong with my code? How should it's look like?
Any help appreciated.
Your controller should
$pricing_feeder = Pricing::find($pricingfeederid)->where('zone_id', $zoneid)->where('is_service_feeder', 1)->first();
Dont forget first() at the end.
Then use like so $pricing_feeder->route->delete();
Try this... $pricing_feeder->route->delete(); Removing () from route()
Your error is on the relation, not the Parent.
not the fanciest but you can delete the route that comes with pricing by adding this method to your route model
public function delete()
{
// delete all related pricing
$this->pricing()->delete();
// delete the route as well
return parent::delete();
}
then just call $pricing_feeder->route->delete();
Ok so I have this model relationships
In Post model
public function user(){
return $this->belongsTo(User::class);
}
In User model
public function post(){
return $this->hasMany(Post::class);
}
and the following code deleted all the posts and the user
$user = \App\User::findOrFail(1);
$user->post[1]->delete();
$user->delete();
Your code does not work, becouse you need to add a first() method call:
$pricing_feeder = Pricing::find($pricingfeederid)->where('zone_id', $zoneid)->where('is_service_feeder', 1)->first();
Than I'd check the returned object if is null. If is not, than you can delete the related relationship and the model as well.
Also, when calling the delete() methods use the relationships as follows:
$pricing_feeder->route->delete();

laravel throws error when returning ->first() in controller

this:
public function show($id)
{
return DB::table('apps')->where('id', $id)->first();//->get();
}
will return an error:
UnexpectedValueException in Response.php line 399:
The Response content must be a string or object implementing __toString(), "object" given.
this will not return an error (but I cant use it since I need an object not array):
public function show($id)
{
return DB::table('apps')->where('id', $id)->get();
}
whats wrong?
Thanks
The DB facade will return a raw PHP object. When returning data from a controller in Laravel it should be a string, array, eloquent model, or response object (ie, view). Since you're returning a raw object, Laravel attempts to cast it to a string, which is the source of your problem.
The best way to resolve this would be use a Model instead of the DB facade
public function show($id)
{
return AppModel::where('id', $id)->firstOrFail();
}
Note: I'm using firstOrFail() here because if an app doesn't exist, Laravel will automatically abort with a 404.
By returning an eloquent model, Laravel knows to automatically cast it to JSON.
If you don't want to use eloquent, then case the object to an array.
public function show($id)
{
return (array)DB::table('apps')->where('id', $id)->first();
}
Laravel will take that array and case it to JSON for you in the response.

Resources