laravel 5多表单数据保存在数据库中

时间:2015-03-06 11:39:45

标签: php laravel laravel-5

我使用两种不同的形式并连接到数据库,它工作正常。但是当我在数据库中将插入值存储为两个不同的行时。

我们什么时候需要使用播种机?我写的是编写正确的laravel 5吗?

控制器文件

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ListFormRequest;
use App\Http\Requests\LoginFormRequest;
use Illuminate\Support\Facades\Input;

use Illuminate\Http\Request;
use Response;
use App\Test;

class testController extends Controller {

  public function test()
  {
    return view('test',array('title' => 'test'));
  }

  public function lockTest(ListFormRequest $test)
  {   $user = new Test();
    $user->firstname = Input::get('firstname');
    $user->password = Input::get('password');
    $user->email = Input::get('email');

    $user->save();

    return view('login');
  }

  public function login()
  {
    return view('login',array('title' => 'login'));
  }

  public function userLogin(LoginFormRequest $test1)
  {
    $user = new Test();
    $user->lastname = Input::get('lastname');
    $user->middlename = Input::get('middlename');
    $user->save();

    return Response::make('Sucessfully Registered!');
  }
}

Route file

<?php

Route::get('/', 'testController@test');
Route::post('login', 'testController@lockTest');
Route::get('login', 'testController@login');
Route::post('userLogin', 'testController@userLogin');


Route::controllers([
  'auth' => 'Auth\AuthController',
  'password' => 'Auth\PasswordController',
]);

播种机文件

   <?php

    use Illuminate\Database\Seeder; 
    use Illuminate\Database\Eloquent\Model;
    use App\Test;

    class TestsSeeder extends Seeder {

      public function run()  {
      DB::table('users')->truncate();


      $qwerty = Input::all();

      foreach($qwerty as $qwertySingle) {
        Test::create([
            'firstname'  => $qwertySingle->firstname,
            'password'   => $qwertySingle->password,
            'email'      => $qwertySingle->email,
            'lastname'   => $qwertySingle->lastname,
            'middlename' => $qwertySingle->middlename,
        ]);
      } 

     DB::table('tests')->insert($qwerty);

     }
   }

模型文件

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

use App\DB;

class Test extends Model {

  protected $guarded = array();
  protected $table = 'tests';

  protected $fillable = ['firstname', 'password', 'email', 'lastname', 'middlename'];
}

1 个答案:

答案 0 :(得分:1)

如果您想使用虚假数据填充数据库,则会使用播种器,因此您可以使用数千个虚拟记录来测试应用程序的水域。

来自播种机的run方法应该如下所示,为您提供一些想法:

  Test::truncate();
  Test::unguard();

  $password = Hash::make('secret');

  foreach (range(1, mt_rand(10, 20)) as $index) {
    Test::create([
        'firstname'  => "first name {$index}",
        'password'   => $password,
        'email'      => "myemail{$index}@mydomain.com",
        'lastname'   => "last name {$index}",
        'middlename' => "middlename {$index}",
    ]);
  }