きょろきょろ(๑´• ₃ •̀๑)

特にWeb系についてのことを書いていきたいと思います。 基本的にメモ書きみたいなものです。

Laravel4でのDataBaseの操作(INSERT,SELECT)とrouteの違う書き方

今回は、index.phpを違う方法で表示させました。

前回は、以下のように表示させましたが、


Route::get('/', function(){  
   return View::make('main.index');
});

 

今回は、このような感じです。

 

Route::get('/', 'HomeController@showWelcome');

 

意味としては、ルートは、HomeController.phpのshowWelcome関数を呼び出すことでindex.phpを表示させています。

 

---------------------------HomeController.php---------------------------------

class HomeController extends BaseController {

     function showWelcome(){

           return View::make('main.index');
     }
}

--------------------------------------------------------------------------------------

 

HomeController.phpは、/app/controllersに配置します。

 

次に、DB接続ですが、/app/config/database.phpで設定します。

ここでは、MySQLのところだけを表示させています。
-------------------------database.php---------------------------------

'mysql' => array(

'driver'    => 'mysql',

'host'      => 'localhost',

'database'  => 'hoge',

'username'  => '',

'password'  => '',

'charset'   => 'utf8',

'collation' => 'utf8_unicode_ci',

'prefix'    => '',

),
---------------------------------------------------------------------------

 

ここに、databaseには、DB名など。。。。まぁみたら分かりますよね。

 

こんな感じに、接続の設定は出来たらしいです。

 

次に、INSERTとSELECTで表示ですが、その関数をまとめた/app/controllers/PostController.phpを下に示します。

--------------------------------------PostController.php------------------------------------------

class PostController extends BaseController{

   function store(){

      DB::table('hoge')->insert([

         'subject'=>Input::get('subject'),

         'grade'=>Input::get('grade'),

         'category'=>Input::get('category'),

         'title'=>Input::get('title'),

         'content'=>Input::get('content')

      ]);

       return Redirect::to('/');

   }

   function index(){

       $posts = DB::table('hoge')->get();

       return View::make('main.index')->with('data',$posts);

   }

}
-------------------------------------------------------------------------------------------------------

 

insertがstore関数に当たり、selectに当たるのがindex関数です。

 

insertの書き方は、insert([//ここには配列]);

'カラム名'=>Input::get('htmlでのname属性')  

って感じです。

insertした後は、ルートディレクトリに戻りたいので、リダイレクトでルートに飛ばします。

 

index関数では、DB::table('DBでのテーブルの名前')->get(); でテーブルのデータを貰って、

 

return View::make('main.index')->with('data',$posts);

でmainフォルダのindex.phpファイルに、dataという変数で値$postsを渡すという意味になります。

 

そんな感じに、index.phpでは、$dataには、SQLのクエリの結果が入っています。

 

最後にroute.php

 

// 実際にDBにデータを入れる

Route::post('/', 'PostController@store');

// すべてのPostを表示する

Route::get('/', 'PostController@index');

 

と書くと、ルートで出力できると思います。

 

index.phpで変数dataをどのようにするかというと、

 

<?php foreach($data as $post){ ?>

 

<?php echo $post->subject." , " ?>

<?php echo $post->grade." , " ?>

<?php echo $post->category." , " ?>

<?php echo $post->title." , " ?>

<?php echo $post->content ?>

 

<?php } ?>

という感じで出力しました。