I have this mysql
table:
+----+-------------------------------+---------+--------------+-------------+
| id | title | chapter | date_release | author |
+----+-------------------------------+---------+--------------+-------------+
| 1 | This is should be title One | 1 | 10/08/2015 | John Robert |
| 2 | This is should be title Two | 1 | 11/08/2015 | John Robert |
| 3 | This is should be title Three | 1 | 12/08/2015 | John Robert |
| 4 | This is should be title Four | 2 | 10/09/2015 | Sir Arthur |
| 5 | This is should be title Five | 2 | 11/09/2015 | Sir Arthur |
| 6 | This is should be title Six | 1 | 13/08/2015 | John Robert |
| 7 | This is should be title Seven | 2 | 12/08/2015 | Sir Arthur |
+----+-------------------------------+---------+--------------+-------------+
In Laravel 5.1 I want to split from the table based chapter
and result view
like this:
<div class="chapter-1">
<span>
...
All content from table of chapter 1 only
...
</span>
</div>
<div class="chapter-2">
<span>
...
All content from table of chapter 2 only
...
</span>
</div>
I have no idea what query function should I do in the controller
and how to display it in laravel view
?
EDITED:
@aldrin27 ask me about my controller, here it is.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class BookController extends Controller {
...
...
public function show($id) {
//
$book = Book::find($id);
return view('books.show', compact('book'));
}
...
...
}
Doing Book::find($id)
will only return a model. What you want is to get a Collection
of models to work with (eg: splitting, grouping, etc.). Use all()
or get()
instead.
Example, Do the following in your controller:
$books = Book::all();
$groupedBooks = $books->groupBy('chapter');
Pass $groupedBooks
to your view and do something like the following in your view file:
@foreach($groupedBooks as $chapter => $books)
<div class="chapter-{{ $chapter }}">
@foreach($books as $book)
<p>{{ $book->title }}</p>
@endforeach
</div>
@endforeach
Note: I think there's a problem with how you setup your relationships. For example, a Book
contains (zero or more?) Chapter
, so those would be two related models instead of using just one model - Book
. But that's just me...