Laravel将数据从控制器传递到视图

时间:2015-10-23 13:25:26

标签: php laravel laravel-5 laravel-5.1

我无法将db结果传递给视图。如果我在Controller端调试它一切正常,所以db查询工作正常,但是当我尝试在视图中获取变量时它表示该变量未定义。

控制器:

$records = DB::table('records')
        ->join('call_charges', function($join)
        {
            $join->on('records.inbound_originating_address_region', '=', 'call_charges.RateDestination')
                ->on('records.inbound_originating_address_type', '=', 'call_charges.RateType');
        })
        ->join('phone_types', 'records.inbound_originating_address_type', '=', 'phone_types.phone_type_id')
        ->orderBy('records.inbound_initiated_utc', 'asc')
        ->get();
return View::make( 'records.index' )->with( 'records', $records );

查看:

@extends('app')

@section('content')

    @if (Auth::check())

    <h2>Call records</h2>

        @if ( !$records->count() )
            No call records to view!
        @else
            <table class="table table-striped table-hover table-condensed table-bordered">
                <thead>
                <tr>
                    <th>Time</th>
                    <th>Out call</th>
                    <th>Duration</th>
                    <th>Cost</th>
                    <th>Billable</th>
                    <th>Country</th>
                    <th>Type</th>
                    <th>Caller</th>
                    <th>Receiver</th>
                </tr>
                </thead>
                <tbody>
                @foreach( $records as $record )
                    <tr>
                    <td>{{ $record->inbound_initiated_utc }}</td>
                    @if ( $record->is_in_call == 1 )
                    <td class="success">Yes</td>
                    @else
                    <td class="warning">No</td>
                    @endif
                    <td>{{ $record->inbound_duration }}</td>
                    <td>{{ $record->session_total_charges }}</td>
                    <td>0</td>
                    <td>{{ $record->inbound_originating_address_region }}</td>
                    <td>{{ $record->inbound_originating_address_type }}</td>
                    <td>{{ $record->inbound_originating_address }}</td>
                    <td>{{ $record->inbound_destination_address }}</td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        @endif

    @endif

    @unless (Auth::check())
        You are not signed in. Please sign in <a href='/auth/login'>here</a>
    @endunless
@endsection

1 个答案:

答案 0 :(得分:3)

return语句更改为

return view("records.index")->with(["records" => $records]);

接下来,使用->count()只能在Eloquent查询(使用->get()->first()之前)返回结果计数。在其中一个闭包之后,需要将逻辑更改为:

@if(count($records) == 0)
No call records to be view!
@else
...
@endif