1

I have two tables.

  1. contenttype
  2. content

contenttype returns me list of content types and I show them on page with foreach. e.g. Ambulance service, Blood Bank , clinic etc. as shown in snapshot.

At the same time I am fetching total number of contents of each type from another table(contents).

I was successful to get total number of contents of each type and show on the blade with foreach. But situation is I want to show the number of contents on every content type. Like this Ambulance sevice 8, Blood Bank 7, Clinic 4. My controller method is:

 public function index()
{
    if (Gate::allows('edit-content', auth()->user())) {
// below line returns list of content type e.g Ambulance service             

 $type = DB::table('contenttype')->distinct('label')->orderBy('label',     'asc')->paginate(10);

//below line counts the number of each content type e.g. Ambulance service 10.

$count = Content::selectRaw('type, count(*)total')->groupBy('type')->get();
return view('admin.content_listing', compact('type', 'count'));
    } else {
        abort(403, "Unauthorized");
    }
}

This is blade code:

@foreach ($count as $c)
  <span class="label label-danger">{{ $c->total }} </span>
@endforeach

This red number list is output: enter image description here

@foreach ($type as $t)
<div class="list-group-item">
<a href="{{ route('content.type.listing', $t->type  ) }}" > {{ $t->label }}
<span class=" pull-right glyphicon glyphicon-search"></span></a>
<a href="{{ route('content.add.form') }}" class="pull-right "><span class="col-md-1 glyphicon glyphicon-plus-sign"></span></a>
</div>
@endforeach

Output is: enter image description here If I place above loop in second loop then Of course it will become nested loop that I don't want.

I need to show Ambulance 8, Beauty clinic 8, Blood Bank 1, etc.

If anybody knows the solution kindly share it! I have tried different ways but no success.

1 Answer 1

1

Rather than creating two queries and attempting to combine their results in the view, have you tried performing a join in a single query? Making certain assumptions about your column names and leaving aside the pagination, the actual SQL would be something akin to:

SELECT contenttype.*, count(content.id) FROM contenttype LEFT JOIN content ON contenttype.id = content.type GROUP BY contenttype.label ORDER BY contenttype.label ASC;

The code necessary to implement this query with Laravel's query builder functionality is pretty well documented in the documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.