i'm building a invoice manager app in laravel 5.6. i'm tryiing to follow the following tut:https://www.youtube.com/watch?v=h6sTdAX6yTs&list=PLVAw_4sB6qJwCloLkV1SudLR0wcgiEXay&index=2 however i get stuck with on the part where i need to display invoices in the index (8:00).
Error: Call to a member function count() on string
index.blade.php:
@extends('layouts.app')
@section('content')
<div>
<div>
<div>
<span>Invoices</span>
<a href="{{route('invoices.create')}}">Create</a>
</div>
</div>
<div>
@if(($invoices->count()))
<table>
<thead>
<th>invoice no.</th>
<th>Grand Total</th>
<th>Client</th>
<th>Invoice Date</th>
<th>Due Date</th>
<th colspan="2">Created At</th>
</thead>
<tbody>
@foreach($invoices as $invoice)
<tr>
<td>{{$invoice->invoice_no}}</td>
<td>{{$invoice->grand_total}}</td>
<td>{{$invoice->client}}</td>
<td>{{$invoice->due_date}}</td>
<td>{{$invoice->created_at->diffForHumans()}}</td>
<td></td>
</tr>
@endforeach
</table>
@else
<div>
<p>
No Invoices were created.
<a href="{{route('invoices.create')}}">Create now!</a>
</p>
</div>
@endif
</div>
</div>
@endsection
InvoiceController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\InvoiceProduct;
use App\Invoice;
use DB;
class InvoiceController extends Controller
{
public function index(){
$title = 'Welkom';
//return view('pages.index', compact('title'));
$invoices = DB::select('SELECT * FROM invoices');
return view('invoices.index')->with('invoices', $title);
}
}
Always use compact to pass variable from controller to view it's easier way.you can use any of the following code.
1st way using eloquent:
public function index(){
$title = 'Welkom';
//return view('pages.index', compact('title'));
$invoices = Invoice::all();
return view('invoices.index',compact('title','invoices'));
}
2nd way using query builder:
use Illuminate\Support\Facades\DB;
public function index(){
$title = 'Welkom';
//return view('pages.index', compact('title'));
$invoices = DB::select('SELECT * FROM invoices');
return view('invoices.index',compact('title','invoices'));
}
3rd way again using query builder:
use Illuminate\Support\Facades\DB;
public function index(){
$title = 'Welkom';
//return view('pages.index', compact('title'));
$invoices = DB::table('invoices')->get();
return view('invoices.index',compact('title','invoices'));
}