m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

laravel5でサンプルアプリ作成

サンプルアプリを作成する

簡単なブログチュートリアルみたいなもので記事の一覧と作成を行う

参考

Laravel5でシンプルなCRUDアプリを開発する : アシアルブログ
※一気にやってもうまくついていけないので少しだけ

DBのマイグレーション

create
$ php artisan make:migration create_articles_table
Created Migration: 2015_05_10_104527_create_articles_table
$ 

※関連したマイグレーションファイルを新規に作成する

ファイルの確認
$ ll database/migrations/
total 12
2014_10_12_000000_create_users_table.php
2014_10_12_100000_create_password_resets_table.php
2015_05_10_104527_create_articles_table.php
$ 

※3つあるけど作ったのは最後のものだけで他のはそのままあった感じ

編集
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticlesTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		// 新規作成
        Schema::create('articles', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title');
            $table->string('body');
            $table->timestamps();
        });
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		// 削除
        Schema::drop('articles');
	}

}
マイグレーション実行
php artisan migrate
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2015_05_10_104527_create_articles_table
$

f:id:m_shige1979:20150510105519p:plain

コントローラーやモデルの用意

雛形を作成する
$ php artisan make:model Article
Model created successfully.
Created Migration: 2015_05_10_105751_create_articles_table
$ php artisan make:controller ArticlesController
Controller created successfully.
$

マイグレーションファイルを作成したけどいらないので削除しておく

モデルを編集する

app/Article.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model {

	// table
    protected $table = "articles";

    // fields
    protected $fillable = ["title", "body"];

}
コントローラーを編集する

app/Http/Controllers/ArticlesController.php

<?php namespace App\Http\Controllers;

use App\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class ArticlesController extends Controller {


    protected $article;

    public function __construct(Article $article){
        $this->article = $article;
    }

	/**
	 * Display a listing of the resource.
	 * 一覧
	 * @return Response
	 */
	public function index()
	{
		//
	}

	/**
	 * Show the form for creating a new resource.
	 * 新規作成
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 * 新規登録
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 * 詳細
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 * 編集
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 * 更新
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 * 削除
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

}

メソッド名にgetとかいれなイカンみたいです

ルーティングを編集

app/Http/routes.php

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

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

Route::get('home', 'HomeController@index');

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

// 追加
Route::get('/', 'ArticlesController@index');
Route::controller('articles', 'ArticlesController');

f:id:m_shige1979:20150510112155p:plain
※まだ、なにも表示していないので空

各機能の作り込み

app/Http/routes.php
<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

// get
Route::get('/', 'ArticlesController@index');
Route::get('articles/index', 'ArticlesController@index');
Route::get('articles/show/{id}', 'ArticlesController@show');
Route::get('articles/edit/{id}', 'ArticlesController@edit');
Route::get('articles/destroy/{id}', 'ArticlesController@destroy');

// post
Route::post('articles/store', 'ArticlesController@store');
Route::post('articles/update/{id}', 'ArticlesController@update');

// resource
Route::resource('articles', 'ArticlesController');
app/Http/Controllers/ArticlesController.php
<?php namespace App\Http\Controllers;

use App\Article;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class ArticlesController extends Controller {


    protected $article;

    public function __construct(Article $article)
    {
        $this->article = $article;
    }

	/**
	 * Display a listing of the resource.
	 * 一覧
	 * @return Response
	 */
	public function index()
	{
		//
        $articles = $this->article->all();
        return view('articles.index')->with(compact('articles'));
	}

	/**
	 * Show the form for creating a new resource.
	 * 新規作成
	 * @return Response
	 */
	public function create()
	{
		// 新規登録画面を表示
        return view('articles.create');
	}

	/**
	 * Store a newly created resource in storage.
	 * 新規登録
	 * @return Response
	 */
	public function store(Request $request)
	{
		// パラメータを取得して保存
        $data = $request->all();
        $this->article->fill($data);
        $this->article->save();

        // 一覧画面へ遷移
        return redirect()->to('/');
	}

	/**
	 * Display the specified resource.
	 * 詳細
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
        $article = $this->article->find($id);

        return view('articles.show', compact('article'));
	}

	/**
	 * Show the form for editing the specified resource.
	 * 編集
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
        $article = $this->article->find($id);

        return view('articles.edit')->withArticle($article);
	}

	/**
	 * Update the specified resource in storage.
	 * 更新
	 * @param  int  $id
	 * @return Response
	 */
	public function update(Request $request, $id)
	{
		//
        $article = $this->article->find($id);
        $data = $request->all();
        $article->fill($data);
        $article->save();

        return redirect()->to('/');
	}

	/**
	 * Remove the specified resource from storage.
	 * 削除
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
        $article = $this->article->find($id);
        $article->delete();

        return redirect()->to('/');
	}

}
resources/views/articles/index.blade.php
@extends('app')

@section('content')
    <h2 class="page-header">記事一覧</h2>
    <div>
        <a href="/articles/create" class="btn btn-primary">投稿</a>
    </div>
    <table class="table table-striped table-hover">
        <thead>
        <tr>
            <th>タイトル</th>
            <th>本文</th>
            <th>作成日時</th>
            <th>更新日時</th>
            <th></th>
        </tr>
        </thead>
        <tbody>
        @foreach($articles as $article)
            <tr>
                <td>{{{ $article->title }}}</td>
                <td>{{{ $article->body }}}</td>
                <td>{{{ $article->created_at }}}</td>
                <td>{{{ $article->updated_at }}}</td>
                <td>
                    <a href="/articles/show/{{{ $article->id }}}" class="btn btn-default btn-xs">詳細</a>
                    <a href="/articles/edit/{{{ $article->id }}}" class="btn btn-success btn-xs">編集</a>
                    <a href="/articles/destroy/{{{ $article->id }}}" class="btn btn-danger btn-xs">削除</a>
                </td>
            </tr>
        @endforeach
        </tbody>
    </table>
@endsection
resources/views/articles/create.blade.php
@extends('app')

@section('content')
    <h2 class="page-header"><a href="/">記事投稿</a></h2>
    <form name="form1" action="/articles/store" method="post">
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
        <div class="form-group">
            <label>タイトル</label>
            <input type="text" name="title" value="" required="required" class="form-control" />

        </div>
        <div class="form-group">
            <label>本文</label>
            <textarea name="body" required="required" class="form-control"></textarea>

        </div>
        <button type="submit" class="btn btn-default">投稿</button>
    </form>
@endsection
resources/views/articles/show.blade.php
@extends('app')

@section('content')
    <h2 class="page-header"><a href="/">記事詳細</a></h2>
    <ul class="list-inline">
        <li>
            <a href="/articles/edit/{{{ $article->id }}}" class="btn btn-primary pull-left">編集</a>
        </li>
        <li>
            <a href="/articles/destroy/{{{ $article->id }}}" class="btn btn-danger pull-left">削除</a>
        </li>
    </ul>
    <table class="table table-striped">
        <tbody>
        <tr>
            <th>タイトル</th>
            <td>{{{ $article->title }}}</td>
        </tr>
        <tr>
            <th>本文</th>
            <td>{{{ $article->body }}}</td>
        </tr>
        <tr>
            <th>作成日時</th>
            <td>{{{ $article->created_at }}}</td>
        </tr>
        <tr>
            <th>更新日時</th>
            <td>{{{ $article->updated_at }}}</td>
        </tr>
        </tbody>
    </table>
@endsection
resources/views/articles/edit.blade.php
@extends('app')

@section('content')
    <h2 class="page-header"><a href="/">記事編集</a></h2>
    <form name="form1" action="/articles/update/{{ $article->id }}" method="post">
        <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
        <div class="form-group">
            <label>タイトル</label>
            <input type="text" name="title" value="{{ $article->title }}" required="required" class="form-control" />

        </div>
        <div class="form-group">
            <label>本文</label>
            <textarea name="body" required="required" class="form-control">{{ $article->body }}</textarea>

        </div>
        <button type="submit" class="btn btn-default">編集</button>
    </form>
@endsection

完成イメージ

f:id:m_shige1979:20150510125847p:plain

所感

サンプルの通りにやろうとしたけどうまく動かなかったのでちょっと変えてやってみました。
なんとか動くようになったのでおk