Laravel many to many values shown in list - php

I have menu items, and menu categories. Categories are assigned to menu items. So a 'pizza' goes under 'dinner' for example.
In my list of menu items, im tring to show the category in the list view but i can't work out how to show the category name in my menu item list as a loop. I have no problem managing this data outside of the context of a list.
This is the index() in my menu items controller
public function index() {
$lists = Menu::orderBy('position')->orderBy('page_name')->paginate( 20 );
return view( 'auth.admin.menu.index' )
->with( 'title', "Menu" )
->with( 'lists', $lists );
}
Loop is . . .
#foreach ($lists as $list)
…
#endforeach
Models are
public function menucats() {
return $this->belongsToMany( 'app\Menucat' )->withTimestamps();
}
public function menu() {
return $this->belongsToMany( 'app\Menu' )->withTimestamps();
}
So the end result of what i am trying to achieve should look like this:
<table>
<thead>
<tr>
<th>id</th>
<th>Menu Items (Menu)</th>
<th>Category (Menucat)</th>
</tr>
</thead>
<tbody>
<tr>
<td>29</td>
<td>Pizza</td>
<td>Dinner</td>
</tr>
<tr>
<td>28</td>
<td>Ice Cream</td>
<td>Desert</td>
</tr>
<tr>
<td>27</td>
<td>Coffee</td>
<td>Hot Drinks</td>
</tr>
</tbody>
</table>

Updated per comment
After re-reading your question I don't believe you need to update your model. If the relationship you want is that many menucats can belong to many menus.
In your controller you would do
public function index() {
$lists = Menu::with('menucats')
->orderBy('position')
->orderBy('page_name')
->paginate( 20 );
return view( 'auth.admin.menu.index' )
->with( 'title', "Menu" )
->with( 'lists', $lists );
}
Then during your loop it would be accessed like this.
#foreach($lists as $list)
...
#foreach($list->menucats as $category)
{{ $category->name }}
#endforeach
...
#endforeach
Updated again per comment
In order to group by menucats, I would get all menucats with their associated menus.
Something like this in your controller should work. The paginate might be tricky.
public function index() {
$lists = Menucats::with(['menu' => function($q){
$q->orderBy('position')
->orderBy('page_name');
])->paginate( 20 );
return view( 'auth.admin.menu.index' )
->with( 'title', "Menu" )
->with( 'lists', $lists );
}
Check out Constraining Eager Loads under Querying Relations

Related

How to fix Show category in laravel

Hi I'm building a ticket system i made tables with heads as:
<table class="table">
<thead>
<tr>
<th>Category</th>
<th>Title</th>
<th>Status</th>
<th>Last Updated</th>
</tr>
</thead>
I'm having trouble calling category name in views:
#foreach ($tickets as $ticket)
#foreach ($categories as $category)
#if ($category->id === $ticket->category_id)
{{ $category->name }}
#endif
#endforeach
My #if statements seems to be wrong i thinks as i can pull all the category names but with #if code seems to be breaking and its showing me nothing.
My routes:
Route::get('my_tickets', 'TicketsController#userTickets');
My Controller Function:
public function userTickets()
{
$tickets = Ticket::where('user_id', Auth::user()->id)->paginate(10);
$categories = Category::all();
return view('tickets.user_tickets', compact('tickets', 'categories'));
}
Update:
My Category Model:
protected $fillable = ['name'];
public function tickets()
{
return $this->hasMany(Ticket::class);
}
&Ticket Model:
protected $fillable = [
'user_id', 'category_id', 'ticket_id', 'title', 'priority', 'message', 'status'
];
public function category()
{
return $this->belongsTo(Category::class);
}
I'm trying to follow this tutorial but i think I'm doing something wrong idk what.
https://scotch.io/tutorials/build-a-support-ticket-application-with-laravel-part-1
https://scotch.io/tutorials/build-a-support-ticket-application-with-laravel-part-2
I think that you are trying to do something like this:
#foreach ($tickets as $ticket)
{{ $ticket->category->name }}
#endforeach
If you made a relation between your classes with belongsTo and hasMany then you can access using $ticket->category->name. If it does not work perhaps you have to get tickets with:
$tickets = Ticket::with('category')->where('user_id', Auth::user()->id)->paginate(10);
You haven't really followed it through. See how it's done in the article
#foreach ($tickets as $ticket)
#foreach ($categories as $category)
#if ($category->id === $ticket->category_id)
{{ $category->name }}
#endif
#endforeach
$ticket->$category is not a valid syntax.

Laravel - sum searched posts price

How can I sum price only for posts that I searched? I have a search page and search is for date, so I search posts by a date. And when I type date that I want I need to sum all posts prices that my search function find for that date. Here is my code.
This is my search in web.php:
Route::get('/search', 'PagesController#search');
Route::post('/search',function(){
$q = Input::get ( 'q' );
$post = auth()->user()->posts()->where('ime','LIKE', '%'.$q.'%')->get();
if(count($post) > 0)
return view('search')->withDetails($post)->withQuery ( $q );
else return view ('search')->withMessage('Nema rezultata Vaše pretrage. Probajte ponovo!');
});
And this is my search function in PagesController:
public function search(){
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('search')->with('posts', $user->posts);
}
And this is my search.blade.php with table footer where is should sum my posts price:
<tfoot>
<tr>
<th>UKUPAN IZNOS: {{ Auth::user()->posts()->sum('cijena') }}€</th>
</tr>
</tfoot>
but when I type this it sums me price for all posts, and I just need for the searched ones. Any suggestions?
... but when I type this it sums me price for all posts, and I just need for the searched ones
This is because you have this line in your view:
<th> ... {{ Auth::user()->posts()->sum('cijena') }} ... </th>
This is executing a different query directly to get the total sum of the cijena. So, regardless of if you constraint your results or not this will keep output the same vale. This different query has any impact on the rest of the queried values.
What you could do is to calculate that value in the main query and return it to the view:
Route::post('/search', function () {
$q = Input::get('q');
$posts = auth()->user()->posts()->where('ime', 'LIKE', '%' . $q . '%')->get();
if (count($posts) > 0)
{
$sum = $posts->sum('cijena'); // <---
return view('search')->withDetails($posts)->withTotal($sum);
} // ^^^^^^^^^^^^^^^^^
else
{
return view('search')->withMessage('Your error message goes here!');
}
});
So now you'll have access to an extra variable $total in your blade file:
<th> ... {{ $total) }} ... </th>
Also, there is no need to define two routes for the same operation, you could reduce all that in one simple method. Additional, you shouldn't execute queries from your front-end. Do as follows:
# web.php
Route::get('/search', 'PagesController#search');
Then in your controller:
# PageController.php
use Illuminate\Http\Request;
// ...
public function search(Request $request)
{
$posts = auth()
->user()
->posts()
->when($request->has('q'), function ($q) { // first check if there is a query
return $q->where('ime', 'LIKE', '%' . request('q') . '%'); // if so, apply filter
})
->get();
if (count($posts) > 0) // checking if there is enough posts..
{
$sum = $posts->sum('cijena'); // if so get the sum of 'cijena'
return view('search')->withDetails($posts)->withTotal($sum);
} // ^^^^^^^^^^^^^^^^
else
{
return view('search')->withMessage('Your error message goes here!');
}
}
Update
This line is the one that throws the error:
<p class="searchp">Rezultati vaše pretrage <b> {{$q}} </b>: </p>
This is because I didn't include a $q variable. Just append it to your response in case you need it:
// ...
return view('search')->withDetails($posts)->withTotal($sum)->with('q', request('q'));
// ...

Laravel AJAX and pagination with no url

I have table displaying many rows, and I'm using pagination and sort function, also I'm using ajax to return number of rows and other ajax to return rows between two dates.
The problem is if I wanted to sort rows and in the same time show some rows between two dates this wont work with me. Because when using ajax there is no url.
public function index()
{
$checks = Checks::orderBy('id', 'asc')->get();
$checks= Checks::sortable()->paginate(10);
return view('home',compact('checks'));
}
public function showpage(Request $request)
{
if($request->ajax())
{
$checks= Checks::orderBy('id', 'asc')->paginate($request->inputpage);
return view('layouts.showcheks',compact('checks'));
}
}
public function getCheckReport(Request $request)
{
if($request->ajax()){
$New=$request->StartDate;
$Old=$request->EndDate;
$checks= Checks::whereBetween('postingdate',[$New,$Old])->sortable()->orderBy('postingdate', 'asc')->get();
return view('layouts.showcheks',compact('checks'));
}
}
showchecks.blade.php
#foreach($checks as $indexKey => $check)
<tr >
<td>{{$check->details}}</td>
<td>{{date('m/d/Y', strtotime($check->postingdate))}}</td>
<td>{{$check->description}}</td>
</tr>
#endforeach
homepage:
<table class="table" id="postTable">
<thead>
<tr>
<th>#sortablelink('details','Details')</th>
<th>#sortablelink('postingdate','Date')</th>
<th>#sortablelink('description','Description')</th>
</tr>
{{ csrf_field() }}
</thead>
<tbody>
#foreach($checks as $indexKey => $check)
<tr >
<td>{{$check->details}}</td>
<td>{{date('m/d/Y', strtotime($check->postingdate))}}</td>
<td >{{$check->description}}</td>
</tr>
#endforeach
</tbody>
</table>
{{$checks->appends(Request::input())->links()}}
use a datatable https://datatables.net/ with ajax that is the best way also u can sorting a rows also..

Laravel 5 check if pivot data is already in database

Got a ManyOnMany system (3 tables, projects, users, project_user)
Many users can work on a project, and a user can have many projects.
When checkbox = checked it sends the database to the pivot table.
Now I'm facing the problem that everytime I click the project/user id will get send to the project_user table.
And I need to have the checkbox already checked when the user is actually added to the project.
So how I see it: the form::checkbox has a third function checked or not checked, and with an if/else statement in my controller.edit I will have a validation somehow. Please help me!
Blade:
#foreach($users as $user)
<tr>
<td>
{{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
</td>
<td>
{!! Form::checkbox('contribute['.$user->id.']', '1', $checkifinproject) !!}
</td>
</tr>
#endforeach
Controller:
public function edit($id, Project $project)
{
$users = User::all();
$project = $this->project->find($id);
if ($users == $project)
{
$checkifinproject = 'checked';
}
else {
}
return view('project.edit', ['project' => $project, 'id' => 'edit', 'project_id' => $id], compact('users'));
}
public function update(CreateProjectRequest $request)
{
if($request->get('contribute'))
{
foreach($request->get('contribute') as $k => $contribute)
{
if($contribute == 1)
{
$project = $this->project->find($request->project_id);
$project->users()->attach($k);
}
}
}
$project = $this->project->find($request->project_id);
$project->fill($request->input())->save();
return redirect('project');
}
Model:
User
public function projects()
{
return $this->belongsToMany('App\Project', 'project_user', 'user_id', 'project_id');
}
Project
public function users()
{
return $this->belongsToMany('App\User', 'project_user', 'project_id', 'user_id');
}
I think the issue is you are comparing two things that will never be the same and trying to determine if that user belongs to the project. A better thing to do would be to query all the users with their projects and as you loop through the users, check to see that the project you are modifying is one of the projects the user belongs to.
That can be done like this...
Controller
public function edit($id, Project $project)
{
$users = User::with('projects')->get();
$project = $this->project->find($id);
return view('projects.edit', ['users' => $users, 'project' => $project]);
}
View
#foreach($users as $user)
<tr>
<td>
{{$user->firstname}} {{$user->middlename}} {{$user->lastname}}
</td>
<td>
{!! Form::checkbox('contribute['.$user->id.']', '1', $user->projects->contains('id', $project->id)) !!}
</td>
</tr>
#endforeach

Symfony2 - Is it possible to create a standalone collection of forms?

I have a table of data I want to be able to edit row-by-row. The most sensible thing do do would be to have each row be its own form. Can I do that in Symfony2 without a linked parent entity? The documentation only shows how to do it with a parent.
Your controller action:
public function gridAction( $criteria ) {
$entities = $this->getDoctrine()
->getManager()
->getRepository( 'Bundle:Entity' )
->findbyCriteria( $criteria );
// criteria presumably involves some gneration from routing
// and may not be a parameter at all
if ( array() != $entities->toArray() ) {
throw
$this->createNotFoundException( 'Unable to find any entities.' );
}
$forms = array_map(function($element) use ($this) {
return $this->createForm(new EntityType()
, $element
, array() // form parameters here
);
});
return $this->render( 'Bundle:Entity:grid.html.twig'
, array(
'forms' => $forms
) );
}
And your twig:
<table class="records_list dataTable" id="CaseloadTable">
<thead>
<tr>
</tr>
</thead>
<tbody>
{% for form in forms %}
<tr>
{{form_widget(form)}}
</tr>
{% endfor %}
</tbody>
</table>
However, you might be better served looking at this:
https://github.com/Abhoryo/APYDataGridBundle

Categories