2015-01-21 70 views
2

我正在嘗試查看Laravel中特定用戶的信息。用戶從下拉菜單中選擇。我試圖用jQuery顯示這個用戶的信息。如何在laravel blade tamplate中使用JSON數據進行模型綁定?

下面是下拉列表中的代碼:

{{ Form::label('Field Force Select:') }} 
<select name="field_force" id="ffID"> 
    <option value=""> --- Please Select a Field Force --- </option> 
    @foreach($users as $user) 
     <option value="{{ $user->id }}"> 
      {{ $user->first_name.' '.$user->last_name }} 
     </option> 
    @endforeach 
</select> 

,這裏是爲$users在路徑文件中的代碼:

public function getAccount() { 
    $group = Sentry::findGroupByName('Field Force'); 
    $users = Sentry::findAllUsersInGroup($group); 
    $currentUser = Sentry::getUser(); 
    return View::make('users/account', 
     array('as' => 'account')) 
       ->with(compact('users', 'currentUser') 
    ); 
} 

從下拉列表中選擇一個用戶後,我用此代碼獲取用戶特定信息:

<script> 
$('#ffID').change(function(){ 
var infoShare= $('.infoStorage'); 
    $.get("{{ url('api/dropDownUserInformation')}}", 
     { option: $(this).val() }, 
     function(data) { 

      $.each(data, function(index, element) { 
       alert(element.id); 

      }); 
     }); 
}); 

這裏是api/dropDownUserInformation路由文件:

Route::get('api/dropDownUserInformation',function(){ 
    $fieldForceID=Input::get('option'); 
    $invoices=Invoice::where('sender_id','=',$fieldForceID)->get(); 
    return Response::json($invoices); 
}); 

到目前爲止,此代碼的工作很好,但是當我試圖通過模型從一個表訪問數據到另一個綁定它不允許我訪問用戶特定的信息。這裏是發票型號:

<?php 
class Invoice extends \Eloquent { 
    protected $fillable = []; 

    public function sales() { 
     return $this->hasMany('Sale', 'invoice_id','sender_id'); 
    } 

    public function accounts() { 
     return $this->belongsTo('SaleAccount'); 
    } 
    public function senderName() { 
     return $this->belongsTo('User','sender_id'); 
    } 
} 

我想訪問users表,使用SenderName()

alert(element.SenderName.first_name); 

在控制檯它顯示了這個錯誤: 類型錯誤:element.SenderName未定義

我能夠做的模型由路由文件將一些變量綁定所以我在劇本寫了這個代碼一般。

這裏是路線文件中的代碼:

public function getUserInfo() { 
    $invoice=Invoice::where('id','=',1)->get(); 
    return View::make('users/account', array(
      'as' => 'account'))->with(compact('invoice')); 
} 

這裏是查看代碼文件:

@foreach($invoice as$inv) 
    {{ $inv->senderName->first_name}} 
@endforeach 

它工作正常,但我不知道該怎麼辦它以JSON格式返回數據之後。

問候

回答

1

我會改變路線:

Route::get('api/dropDownUserInformation',function(){ 
    $fieldForceID = Input::get('option'); 
    $invoices = Invoice::where('sender_id','=',$fieldForceID) 
     ->join('users', 'invoices.sender_id', '=', 'users.id')->get(); 
    return Response::json($invoices); 
}); 

這應該可以訪問在你的jQuery函數如下...

alert(element.first_name); 
相關問題