How can I make pagination of a findorfail method in laravel - 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')

Related

Custom method not work on HasMany relation

I trying to call a custom method from a model by relation.
User Model:
class User extends Model
{
public function files()
{
return $this->hasMany(Files::class, 'file_id', 'id');
}
}
File Model:
class Files extends Model
{
public function cover()
{
dd('blah blah');
}
}
In my controller I said:
$user = User::find(1);
$user->files()->cover();
But I will get this error:
Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::cover()
What is the problem in my code?
Basically you are calling your cover() method over the collection. That's why that is not working.
You are using hasMany Laravel relationship. And this hasMany returns collection of related records(items). And yo can't call any model function on that directly.
But if you wan to call function on this. you need to firstly loop the items, like below example:-
$user = User::find(1);
foreach($user->files() as $file) {
$file->cover();
}
Above code will provide you output. Try this.
If you want to get all the covers of you files, you can do this :
$user = User::with('files.cover')->find(1);
$covers = $user->files->pluck('cover')->flatten();
I want to use this method to check and then store the cover. because I need to check the cover before insert I couldn't use create method, it will be an alias to create. so I couldn't overwrite to create method?
From this, you can do the following:
foreach($user->files as $file){
$cover = $file->cover()->firstOrCreate(['attribute' => $value]);
// If you want to check if you just created the cover
if($cover->wasRecentlyCreated){
// Do stuff
}
}

Getting data from two separate models in laravel

I wanted to get data which is related to an id and I used the find($id) method to get those data, now I wanna get data from two tables which have one to many relationship.
How can I get data which is related to the same id from two table?
I try to this way but it hasn't worked:
public function show($id)
{
$post=Clients::find($id);
return view('pet.shw',['post'=>$post,'pets'=>$post->pets]);
}
Why you dont use with() I have simple solution but maybe not best solution:
Post::with('pets')->where('id',$id)->first();
Maybe below code is work to i dont test it:
Post::with('pets')->find($id);
Of course you should have comments method in your Post Object:
public function pets(){
return $this->hasMany(Pet::class);
}
hope help
You need to first define a relationship between your Client model and Pet model
So, in App\Client, you would have the following relationship:
public function pets()
{
return $this->hasMany(Pet::class);
}
and in App\Pet, you would have the following relationship:
public function client()
{
return $this->belongsTo(Client::class)
}
You should then be able to do this in your Controller:
public function show($id)
{
$post = Client::with('pets')->find($id);
return view('pet.shw')
->withPost($post);
}
and accesses your relationship like this in the pet.shw view:
foreach($post->pets as $pet) {}
For more information read about Eloquent Relationships

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 relationship `whereNotIn` other table

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().

Laravel + Eloquent - Passing through custom function first

What I want to do is quite simple I think. In my controller I have the code:
$list = SiteCategory::where('type','=','A')->get();
Which returns a standard eloquent collection object. However, sometimes when I retrieve categories, I want them to be ordered in a specific way first. So can I have some function in my model like:
Class SiteCategory extends Eloquent {
public function mySpecialFunction(){
// retrieve all categories, manipulate them in some way and return.
}
}
How do I then call this function? I don't understand, and the tutorials and questions I've read do not help. For example, in this question on SO, he seems to imply he can call his function something like this:
SiteCategory->mySpecialFunction()
I don't get it?
You can use a scope method inside your Model like this
Class SiteCategory extends Eloquent {
public function scopeMySpecialFunction($query){
// retrieve all categories, manipulate them in some way and return.
}
}
Then you can call this function like normal built in Eloquent functions like
SiteCategory::mySpecialFunction();
If you want to pass any arguments into this function then you can add parameters like this
public function scopeMySpecialFunction($query, $param1, $param2){
// retrieve all categories, manipulate them in some way and return.
}
Notice the first $query parameter, it's the first parameter of a scope method and $query is an instance of Illuminate\Database\Eloquent\Builder, you can use $this inside that function and can chain methods like
SiteCategory::mySpecialFunction()->find(1);
In this case you have to return the $query from your function to chain other methods, like:
public function scopeMySpecialFunction($query, $param1, $param2){
// do something
return $query;
}

Resources