issue with pagination in laravel - php

my controller code
$posts = Categorie::where('parent_id',$id)->paginate(2);
model code :
public function post1(){
return $this->hasMany(post::class, 'category_id');
}
view page code :
#foreach ($posts as $cat)
#foreach ($cat->post1 as $post)
{{Debugbar::info($post->body)}}
<br>
#endforeach
#endforeach
and for pagination I used code :
{{ $posts->links() }}
all are working fine, data is fetched, I checked in the debugger. and pagination link also shown. I have 3 rows then fetched 2 rows on 1 page and other page shows another row. but problem is that it shows all data on page 1 when I clicked on pagination link page2 then shows a blank page.
how my pagination work properly

no method "links" you can try this
{{ $posts->render() }}

You are currently paginating categories, not posts.
Define the reverse relationship of post1 (if you haven't already):
class Post extends Model {
public function category() {
return $this->belongsTo(Categorie::class, 'category_id');
}
}
Then query the Post model and use whereHas():
$posts = Post::whereHas('category', function($query) use($id) {
$query->where('parent_id', $id);
})->paginate(2);
{{ $posts->links() }}
#foreach ($posts as $post)
{{ $post->body }}
#endforeach

Related

how to show multiple category name from checkbox value in eloquent relationship laravel

firstly, i'm a newbie in laravel.
i insert a array data as a string in server.
column name "category_id" & value like "1,2,3,4".
Now i just want to show these id's category name with eloquent relationship.
Using laravel latest version.
view page
{{$category_var = explode(',',$post->category_id)}}
#foreach($category_var as $category)
#if($category)
<span class="badge mb-3">{{$post->category->category}} </span>
#endif
#endforeach
class page
public function category(){
return $this-> belongsTo(Category::class);
}
Controller page
public function index()
{
$posts = post::paginate(9);
return view('pages/home',compact('posts'));
}
anything else need just ask me.
Thanks
just use the benefits of models and relation like below:
#foreach($posts as $post)
#foreach($post->category as $category)
<span class="badge mb-3">
{{ $category->(what ever you want from category model) }}
</span>
#endforeach
#endforeach

Not getting question Model's values in Laravel 5.6

I'm using Laravel 5.6 and I have created two Models Question and User Model and these are linked to each other using one to many relation as:
Question Model
public function user() {
return $this->belongsTo('App\User');
}
User Model
public function questions() {
return $this->hasMany('App\Question');
}
And my controller code is:
public function index()
{
$user = User::all();
return view('home', compact('user'));
}
So, i'm trying to get question title and I have written this code in blade:
#foreach($user as $user)
{{ dd($user->questions->questions_title) }}
#endforeach
But getting error undefined index questions_title, but if only write this {{ dd($user->questions) }} it gave me all questions, so how to fix it.
I have also tried {{ dd($user->questions['questions_title']) }} but not fixed.
You'll want to loop over your questions relationship to see your question:
#foreach($user as $u)
#foreach($u->questions as $question)
{{ dd($question->questions_title) }}
#endforeach
#endforeach
Note: I changed $user to $u
In your controller, you are not eager loading your questions relationships. Change your code to the following:
public function index()
{
$user = User::with('questions')->get();
return view('home', compact('user'));
}
Using the with() method will load all specified relationship with the eloquent query. After this, you will need to loop through the questions collection using the ->each() collection method.
#foreach($users as $user)
#foreach($user->question as $question)
{{ $question->question_title }}
#endforeach
#endforeach
No need for two foreach loops we can simply use one like below:
#foreach ($user->questions as $question)
{{ dd($question->questions_title) }}
#endforeach

Laravel - getting relation in loop - best practices

Just an example:
let's say I have Post model, and the Comment model. Post, of course, have Comments, one-to-many relation.
I have to display list of posts with comments below it.
I'll get my posts in the controller:
$posts = Post::get(), I'll pass it to the blade view and then I'll loop through it
#foreach($posts as $post)
{{ $post->title }}
{{ $post->comments }}
#endforeach
where $post->comments is some relation
public function comments()
{
return $this->hasMany(Comment::class);
}
As we know, that query will be executed many times.
Now my question: how we should optimize it?
Return Cache::remember in the getter?
Get (somehow?) those comments, when getting the posts in one query? Something like join query? I know that I can write that kind of query, but I'm talking about Eloquent's query builder. And then how get the comments within the loop? Wouldn't {{ $post->comments }} call the relation again instead of getting stored data?
Different solution?
You can do $posts = Post::with('comments')->get() to eager load the comments with the post. Read more about it in the documentation: https://laravel.com/docs/5.7/eloquent-relationships#eager-loading
Also, to display the comments you would want to add another foreach loop. It would look something like this:
#foreach($posts as $post)
{{ $post->title }}
#foreach($post->comments as $comment)
{{ $comment->title }}
#endforeach
#endforeach
You’ve probably cached some model data in the controller before, but I am going to show you a Laravel model caching technique that’s a little more granular using Active Record models
Note that we could also use the Cache::rememberForever() method and rely on our caching mechanism’s garbage collection to remove stale keys. I’ve set a timer so that the cache will be hit most of the time, with a fresh cache every fifteen minutes.
The cacheKey() method needs to make the model unique, and invalidate the cache when the model is updated. Here’s my cacheKey implementation:
public function cacheKey()
{
return sprintf(
"%s/%s-%s",
$this->getTable(),
$this->getKey(),
$this->updated_at->timestamp
);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function getCachedCommentsCountAttribute()
{
return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
return $this->comments->count();
});
}
yes u can do like that in controller
$minutes = 60;
$posts = Cache::remember('posts', $minutes, function () {
return Post::with('comments')->get()
});
in blade u can get like that
#foreach($posts as $post)
{{ $post->title }}
#foreach($post->comments as $comment)
{{ $comment->title }}
#endforeach
#endforeach
for more information read this article

Getting Articles category laravel

I want to get category name of articles. This is my CategoriesController:
public function show(Category $category)
{
$articles = $category->articles()->latest()->paginate(5);
return view('categories.index', compact('articles'));
}
When I try to do it like this: {{$articles->category()}}
I'm getting this error: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Database\Eloquent\Collection' does not have a method 'category'
You already have the category getting passed to your controller action, so just pass that instance to your view rather than trying to grab it from every article item and potentially adding more database queries to your controller action.
public function show(Category $category)
{
return view('categories.index', compact('articles', 'category'));
}
$articles would, in this case, be a collection of several articles. Therefore you can't simply do {{ $articles->category }}.
This should work, however:
#foreach ($articles as $article)
{{ $article->category }}
#endforeach

Laravel 4: how to display a preview of a post using eloquent ORM/blade

I built a simple cms in Laravel 4. At the moment the main site index shows a list of all posts including the body of the post.
I want to only show, for example, the first 100 letters of the body of my post as a preview before viewing the whole article on my show.blade.php page.
The relevant part of the index.blade looks like this:
#foreach($posts as $post)
...
<p>{{ $post->body }}</p>
And the relevant part of my DisplayController looks like this:
public function index()
{
$posts = $this->post->orderBy('id', 'DESC')->get();
return View::make('index', compact('posts'));
}
How would I display only the first 100 characters of each post on my index page (as an example)?
#foreach($posts as $post)
<p>{{ substr($post->body, 0, 100) }}</p>
#endforeach

Categories