Laravel 8: How to add pagination after retrieving data from ManyToMany Relationship - php

I'm working on a forum project using Laravel 8, and in this project, I have made a page for getting all the questions with specific tag. Here is the the method to do that:
public function tag($name)
{
$tag = \App\Models\Tag::findOrFail($name);
return view('tag',[
'single' => $tag
]);
}
And then inside tag.blade.php:
#foreach($single->questions as $one)
...
#endforeach
But now I need to add pagination for this page, so if questions are more than a custom number, they can navigate to other pages.
In fact I had already added pagination to my other page which shows all the entire questions:
public function allQuestions()
{
$all = Question::latest()->paginate(20);
return view('questions.allquestions',[
'all' => $all
]);
}
But I don't know really how to add this feature to tag() method.
So if you know how to add this pagination, please let me know...
I would really appreciate any idea or suggestion from you guys.
Thanks in advance.

Theres 2 choices for this:
First Choice:
public function tag($name)
{
$tag = \App\Models\Tag::findOrFail($name);
$questions = $tag->question()->paginate(10);
return view('tag',[
'single' => $tag, 'questions' => $questions
]);
}
Then, on your view, you can just loop through the questions.
#foreach ($questions as $question)
... fill this
#endforeach
{!! $questions->render() !!}
Second Choice:
public function tag($name)
{
$tag = \App\Models\Tag::findOrFail($name);
$tag->setRelation('questions',$tag->questions()->paginate(10));
return view('tag',[
'single' => $tag
]);
}
Then, on your view, you can just loop through the questions.
#foreach ($single->questions as $question)
... fill this
#endforeach

Related

Form select box {!!Form::select()!!} Laravel

I'm using Laravel Collective Form builder in my view and i'm populating this select box from a table in my DB like this
I am having an issue with my values not matching up and my dropdown is also giving me the values as an array...
Here's what I have in my PostsController:-
public function edit(Post $post)
{
$categories = Category::all()->pluck('title', 'id')->toArray();
return view('posts.edit')->withPost($post)->withCategories($categories);
}
and here's my view edit.blade.php:-
{{ Form::label('category_id', 'Category :')}}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}
So I need little help?
Here's the value issue I was talking about:
enter image description here
Here's the array issue I was talking about:
enter image description here
no need to use toArray() pluck method automatically create an array.
try this
$categories = Category::pluck('title', 'id');
First of all your code seems like not proper.
$categories = Category::all()->pluck('title', 'id')->toArray();
should be
$categories = Category::pluck('title', 'id')->toArray();
Firstly update you controller function. I think that will help:-
public function edit(Post $post)
{
$categories = Category::pluck('title', 'id')->toArray();
return view('posts.edit', [
'post' => $post,
'categories' => $categories
]);
}
Try this code and let me know need help.

How to get pagination in laravel 5

In controller:
function show($feast_id)
{
$feastMenu = Feast::find($feast_id);
$feastMenu->load('images', 'menu', 'users');
$feastMenu->chef->load('chefMeta');
$feastMenu = $feastMenu->toArray();
return view('feasts.showFeastMenu', compact('feastMenu'));
}
in views
#foreach($feastMenu['menu'] as $k => $menu)
Menu“{{$feastMenu['name']}}”({{count($feastMenu['menu'])}} course meal)
{{$menu['name']}}
#foreach($menu['menu_items'] as $item)
{{$item['name']}}
{{$item['description']}}
#endforeach
#endforeach
How can I set pagination into this please suggest in laravel I am using laravel 5. I have used relation into the controller and pass those toArray
There are a few things i have questions about... but first you should really take a look at the documentation https://laravel.com/docs/5.4/pagination it does a really good job explaining how to do what you want...
Anyways to answer you question i would do it this way... (note how i changed the views due to the returning collection instead of array). Also this will be under the assumption that you are using bootstrap.. if you are not you will need to look over the documentation to see how to add the pagination links
Controller:
function show($feast_id)
{
$feastMenu = Feast::find($feast_id)->simplePaginate(5);
$feastMenu->load('images', 'menu', 'users');
$feastMenu->chef->load('chefMeta');
return view('feasts.showFeastMenu', compact('feastMenu'));
}
View:
#foreach($feastMenu->menu as $k => $menu)
Menu“{{$feastMenu->name}}”({{$feastMenu->menu->count())}} course meal)
{{$menu->name}}
#foreach($menu->menu_items as $item)
{{$item->name}}
{{$item->description}}
#endforeach
#endforeach
{{ $feastMenu->links() }}

getting multiple rows from db that are associated to previous selected rows. laravel 4.2 php

so here is my problem,
for a school project i have to make a quiz website in which a normal user should be able to play a quiz, so i have to show all the questions associated to the quiz and all the answers associated to the question, but when i try to do so it only shows the answers that are associated to the final question. here is my code:
// select the clicked quiz.
$quiz = Quiz::find($id);
// get all the question and answer records from db that are associated to the selected quiz.
$questions = DB::table('questions')->where('quiz_id', $id)->get();
foreach($questions as $question)
{
$answers = DB::table('answers')->where('question_id', $question->id)->get();
}
return View::make("quizzes.makeQuiz", [
"quiz" => Quiz::find($id)
])->with('quiz', $quiz)->with('questions', $questions)->with('answers', $answers);
and here is the html (using blade):
<h3>{{ $quiz->name }}</h3><br/>
#foreach($questions as $question)
<h4>{{ $question->question }}</h4>
#foreach($answers as $answer)
<p>{{ $answer->answer }}</p>
#endforeach
#endforeach
when i try to do this without a foreach i get an error that says 'Trying to get property of non-object'. i know why i get that error because obviously $questions isn't an object.
help is very much appreciated! thanks for reading!
edit*
alright so i have now changed my code to look like this:
$questions = Question::where('quiz_id', $id)->get();
foreach($questions as $question)
{
$answers = Answer::where('question_id', $question->id)->get();
}
$data = [
'quiz' => Quiz::find($id),
'questions' => $questions,
'answers' => $answers
];
return View::make("quizzes.makeQuiz", $data);
the html is basically the same, it returns the quiz and all the questions associated. but unfortunately it only returns the answers associated to the final questions while each questions has 3 answers. i think the problem lies in $answers but i don't know exactly what i am doing wrong here :( please help! thanks!
*edit
I asked this question a second time and it solved my problem, here is the link:
retrieving multiple records associated to multiple records laravel 4.2
Rewrite your return statement as such:
$data = [
'quiz' => Quiz::find($id),
'questions' => $questions,
'answers' => $answers
];
return View::make("quizzes.makeQuiz", $data);
You are currently returning an array AND trying to return chained variables. Most likely your $questions variable never reaches the view because you are passing an array first.
Plus the fact you were trying to collect the Quiz model twice for some reason is just wrong.
Also - why are you mixing Eloquent and Fluent statements to get your models? Stick to one or the other unless the situation warrants it.

Laravel PHP: Display array elements in drop down list alphabetically without using sort()

I have a Laravel PHP Photo Gallery application that allows the user to create an album and then insert photos into an album of their choice from a drop down list. This requires the user to create the album first since the drop down list is dynamic based on which albums actually exist. The drop down list is currently functioning properly but it does not display albums (array elements) alphabetically.
I've tried using the 'sort()' method but the problem is that the array element ids then become switched/re-sorted when doing so. I do not want the array ids to be re-sorted since this will put photos into the wrong albums.
So I want to know if there is a way to display the albums alphabetically in a drop down list while not re-sorting their array element ids.
Controller:
public function create()
{
$stoneArray = $this->stone->all()->toArray();
if (empty($stoneArray)) {
$dropdown[0] = 'There are no stones';
}
foreach ($stoneArray as $stone) {
$dropdown[$stone['stone_id']] = $stone['stone_name'];
// sort($dropdown); /* This re-sorted the array element ids */
}
$data = array('type' => 'stone_photo', 'dropdown' => $dropdown);
$this->layout->content = \View::make('forms.stones.new-photo', $data);
}
View:
<div class="form-group">
{{ Form::label('stone_id', 'Stone: ') }}
{{ Form::select('stone_id', $dropdown, array('class' => 'form-control')) }}
</div>
Any help is greatly appreciated! Thank you!
EDIT
I'm making some assumptions here about your file structure, but it should give you the idea.
In: app\Acme\repositories\Eloquent\EloquentStoneRepository.php or whatever you called it, there's a function:
public function all()
{
return Stone::all();
}
(I think that's what it looks like, but I'm not positive). Try changing that to:
public function all()
{
return Stone::orderBy('column_name', 'asc')->get();
}
If you use all() somewhere else and don't want it sorted, consider adding another function:
public function all_sorted()
{
return Stone::orderBy('column_name', 'asc')->get();
}
Hope that helps!
Edit:
Changed ->all() to ->get() so eloquent can properly sort it.

Laravel 4 : trying to get variable from same page

I'm new to Laravel and I'm getting an error which I think has more to do with logic than anything else but I can't quite seem to grasp how to overcome it.
So, I have a page with a simple form to search for a particular string in my database. But I want to have the result show up on the same page.
Here's what I have so far:
This is my Route.php:
Route::get('/', 'HomeController#index');
Route::post('find', 'HomeController#find');
This is my HomeController:
public function index()
{
return View::make('index');
}
public function search()
{
return View::make('index');
}
public function find()
{
$match = Input::get('find');
if($match) {
$results = Book::where('title', 'like', '%'.$match.'%')
->orWhere('author', 'like', '%'.$match.'%')
->get();
return View::make('index', array('results', $results));
} else {
return Redirect::to('/')->with('flash_error', 'No string added!');
}
}
And my View (index.blade.php):
{{ Form::open(array('url' => 'find', 'method' => 'POST')) }}
{{ Form::text('find', '', array('class' => 'search-query', 'placeholder' => 'Search')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-info')) }}
{{ Form::close() }}
#if (Session::has('flash_error'))
{{ Session::get('flash_error') }}
#endif
#foreach ($results as $result)
{{$result->title}}
#endforeach
(eventually the foreach will be replaced by some ajax loading to display each result)
And the error says "undefined variable: results" and shows the foreach.
I get why that error shows up since on the first pass to this page the results haven't been loaded yet but how can I overcome this? I really want the data to be shown on the same page without having to go to another page to display them.
Like I said, I think this is mostly logic related (although I'm very new to Laravel so it might be that too)
Any help would be greatly appreciated !
you need to pass an associative array as your second param of the make method
return View::make('index', array('results' => $results);
The problem here is that in your use of index.blade.php in multiple controllers, you forgot which controllers provide which variables (and as a result, which variables may be omitted).
When you request / (HomeController#index), index.blade.php is rendered, but since no $results are passed to the view, you see the Undefined Variable warning. This is not a problem in HomeController#find, because you define $results. To combat this, you'll need to do something along the lines of an isset() check on $results before you foreach over it. Like so:
#if(isset($results))
#foreach ($results as $result)
{{$result->title}}
#endforeach
#endif
Your logic may vary based on your page's layout (you might want to add an else and display some alternate placeholder content).
Also, if abstracting the call to View::make() with $results into index_gen() isn't keeping your code DRY, then I'd suggest replacing it in find() with the call to View::make().

Categories