2014-01-07 2 views
0

Я немного недоумен, почему данные формы не отправляются в db из приведенного ниже кода. Я немного новичок в Laravel 4, и я предполагаю, что мне не хватает кода в коде. Когда я нажимаю кнопку «Отправить», я перенаправляюсь, но запись не добавляется в базу данных. Помощь была бы оценена, указывая на то, что мне не хватает. Огромное спасибо.Laravel 4 - Данные формы не отправляются в db

EntriesController.php

<?php 

class EntriesController extends BaseController { 

#Handles "GET /" request 
public function getIndex() 
{ 
    return View::make('home')->with('entries', Entry::all()); 
} 

#Handles "POST /" request 
public function postIndex() 
{ 
    $entry = array(
     'username' => Input::get('frmName'), 
     'email' => Input::get('frmEmail'), 
     'comment' => Input::get('frmComment') 
    ); 

// save the guestbook entry to the database 
Entry::create($entry); 

return Redirect::to('/'); 
} 
} 

?> 

home.blade.php

<html> 
<head> 
    <title>Laravel 4 Guestbook</title> 
</head> 
<body> 
    @foreach ($entries as $entry) 
     <p>{{ $entry->comment }}</p> 
     <p>Posted on {{ $entry->created_at->format('M jS, Y') }} by 
      <a href="mailto:{{ $entry->email }}">{{ $entry->username}}</a> 
     </p><hr> 
    @endforeach 

    <form action="/" method="post"> 
     <table border="0"> 
      <tr> 
       <td>Name</td> 
       <td><input type="text" name="frmName" value="" size="30" maxlength="50"></td> 
      </tr> 

      <tr> 
       <td>Email</td> 
       <td><input type="text" name="frmEmail" value="" size="30" maxlength="100"></td> 
      </tr> 
      <tr> 
       <td>Comment</td> 
       <td><input textarea name="frmComment" row="5" cols="30"></textarea></td> 
      </tr> 

      <tr> 
       <td></td> 
       <td> 
        <input type="submit" name="submit" value="submit"> 
        <input type="reset" name="reset" value="reset"> 
       </td> 
      </tr> 
     </table> 
    </form> 
</body> 

Entry.php

<?php 

Начальный класс расширяет красноречивый {

/** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'entries'; 

} 

?> 

routes.php

Route::controller('/', 'EntriesController'); 

ответ

0

Попробуйте это:

EntriesController.php

<?php 

class EntriesController extends BaseController { 


    public function index() 
    { 

     $entries = Entry::all(); 

     //->with('entries', Entry::all()); 
     //in Laravel 4.1, variable pass with 'With' will be process via Session. 
     // changed 'with' to 'compact' 

     return View::make('home', compact('entries')); 
    } 


    public function store() 
    { 
     $entry = array(
      'username' => Input::get('frmName'), 
      'email' => Input::get('frmEmail'), 
      'comment' => Input::get('frmComment') 
     ); 

     // save the guestbook entry to the database 
     Entry::create($entry); 

     // Name route `index` 
     // resourceful controller create 7 routes for you 
     // http://laravel.com/docs/controllers#resource-controllers 

     return Redirect::route('index'); 
    } 
} 

routes.php

Route::resource('/', 'EntriesController'); 

home.b lade.php

<html> 
<head> 
    <title>Laravel 4 Guestbook</title> 
</head> 
<body> 
    @foreach ($entries as $entry) 
     <p>{{ $entry->comment }}</p> 
     <p>Posted on {{ $entry->created_at->format('M jS, Y') }} by 
      <a href="mailto:{{ $entry->email }}">{{ $entry->username}}</a> 
     </p><hr> 
    @endforeach 

    {{ Form::open(array('route' => 'store')) }} 
     <table border="0"> 
      <tr> 
       <td>Name</td> 
       <td><input type="text" name="frmName" value="" size="30" maxlength="50"></td> 
      </tr> 

      <tr> 
       <td>Email</td> 
       <td><input type="text" name="frmEmail" value="" size="30" maxlength="100"></td> 
      </tr> 
      <tr> 
       <td>Comment</td> 
       <td><input textarea name="frmComment" row="5" cols="30"></textarea></td> 
      </tr> 

      <tr> 
       <td></td> 
       <td> 
        <input type="submit" name="submit" value="submit"> 
        <input type="reset" name="reset" value="reset"> 
       </td> 
      </tr> 
     </table> 
    {{ Form::close() }} 
</body> 
+0

Я пробовал ваше предложение с отключением тегов формы, и хотя он не вызывает ошибку или не перенаправляет меня, он не добавляет новые значения формы на страницу. Он просто представляет и не отображает только что представленную новую информацию. –

+0

Привет, вы хотите использовать контроллер ресурсов вместо restfull controller? Зачем? прочитайте: http://philsturgeon.co.uk/blog/2013/07/beware-the-route-to-evil – Anam

+0

Если вы хотите использовать контроллер ресурсов, дайте мне знать. – Anam

0

Похоже, ваша форма Действие указывает на неправильное место. Путь '/' - ваш маршрут getIndex(). Я считаю, что это должно быть:

<form action="postIndex" method="post"> 
     <table border="0"> 
      <tr> 
       <td>Name</td> 
       <td><input type="text" name="frmName" value="" size="30" maxlength="50"></td> 
      </tr> 
+0

Хмм Я просто попытался что и получил следующее сообщение об ошибке - Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException метод контроллера не найден. –

Смежные вопросы