2016-05-12 46 views
1

我有一個接受參數的自定義路由。這是:在laravel中獲取create方法的參數值時返回null

Route::get('reservation/{id}/create', 
     ['as' => 'reservation.create', 'uses' => '[email protected]' 
]); 

我有這個變量保護$ student_id。該ID被分配到ReservationController的創建方法的參數,如下圖所示:

class ReservationController extends Controller 
{ 
    protected $student_id; 

    public function index() 
    { 
     return $this->student_id; 
    } 

    public function create($id) 
    { 
     $this->student_id = $id; 
     $subjects = Subject::with('sections')->get(); 

     return view('reservation.form',compact('subjects')); 
    } 

    public function store(Request $request) 
    { 

     $subject = new Reservation(); 

     $subject->section_subject_id = $request->sectionSubjectId; 

     $subject->student_id = $this->student_id; 

     $subject->save(); 

    } 
} 

當返回$ id參數的創建方法,我得到確切的ID號。我還爲$ student_id分配了$ id。但是,當在商店方法上分配$ student_id時,我會得到空值。我知道我在這裏做錯了,有人可以幫我解決這個問題。

好吧,讓我添加一些信息:在我的網址時使用reservation.create路由我有這個地址localhost:8000/reservation/1 /創建 該網址的數字1是我想要的學生ID在我的商店方法中獲取並分配給student_id。

我也有這種形式的看法:

form.blade.php

<body> 
@foreach($subjects as $subject) 
@foreach($subject->sections as $section) 
    <tr> 
    <td>{{ $section->section_code }}</td> 
    <td>{{ $subject->subject_code }}</td> 
    <td>{{ $subject->subject_description }}</td> 
    <td>{{ $section->pivot->schedule }}</td> 
    <td>{{ $subject->units }}</td> 
    <td>{{ $section->pivot->room_no }}</td> 
    <td> 
    <button 
     v-on:click="addSubject({{ $section->pivot->id }})" 
     class="btn btn-xs btn-primary">Add 
     </button> 

     <button class="btn btn-xs btn-info">Edit</button> 
    </td> 
    </tr> 
    @endforeach 
    @endforeach 
</body> 

同時我讓我們vue.js和VUE資源

all.js

methods:{ 
    addSubject: function(id){ 

    this.$http({ 
    url: 'http://localhost:8000/reservation', 
    data: { sectionSubjectId: id }, 
    method: 'POST' 
    }).then(function(response) { 
     console.log('success'); 
    },function (response){ 
     console.log('failed'); 
     }); 
    } 
} 
+0

因爲student_id數據爲空,則使用 $主語> student_id數據= $請求 - > ID;或$請求 - > student_id數據或任何你使用 –

回答

0

您正試圖將變量保存在$this->student_id中,並稍後以其他方法使用它。這不是如何工作的。事情是這些方法用於不同的HTTP請求,所以變量將不會保留。

您應該將此變量從reservation.form視圖傳遞到store()方法。

您可以使用Request對象。在一個觀點:

<input name="studentId" type="hidden">{{ $studentId }}</input> 

並在控制器:

$studentId = $request->get('studentId'); 

或者,如果你想在一個store()方法來使用它,你可以把它作爲第二個參數。

public function store(Request $request, $studentId) 
{ 
    echo $studentId; 
+0

的名字是的,爲什麼不呢?此外,您可以使用現有代碼並在'sectionSubjectId'旁邊添加'studentId',並以與獲得'sectionSubjectId'相同的方式從Request對象中獲取它。 –

+0

謝謝。我想過安全問題。但忘記了。問題是在我的form.blade上的addSubject方法傳遞兩個參數似乎不起作用。我所做的是{{$ section-> pivot-> id,$ student_id}}。我在這裏錯過了什麼嗎? – Jearson

+0

好吧,我得到了addSubject({{$ section-> pivot-> id}},{{$ student_id}})。 – Jearson