2019年1月16日 星期三

建立文章系統流程:全部程式

建立文章系統流程:全部程式

*route
*查route設定
*controller
*model
*view
*Form Requests
*migration
*seeder
*env

=========================
=========================
*route:

routes\web.php

Route::get('/','ArticleController@index');
Route::resource('article','ArticleController');

*查route設定:

php artisan route:list

=========================
*controller:

app\Http\Controllers\ArticleController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Article;
use App\Http\Requests\ArticleRequest;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $query=Article::all();
        return view('article.index',compact('query'));
    }

    /**新增資料:form
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('article.create');
    }

    /**新增資料
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(ArticleRequest $request)
    {
        Article::create($request->all());
        return redirect('article');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return 'show';
    }

    /**編輯資料:form
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $query=Article::find($id);
        return view('article.edit',compact('query'));
    }

    /**編輯資料
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(ArticleRequest $request, $id)
    {
        //方法1
        // Article::where('id',$id)->update([
        //     'title' => $request->title,
        //     'content' => $request->content
        // ]);
       
        //方法2
        $article = Article::findOrFail($id);
        $article->update($request->all());
       
        return redirect('article');
    }

    /**刪除資料
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Article::destroy($id);
        return redirect('article');
    }
}

=========================
*model:

app\Article.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $table='articles';

    protected $primaryKey='id';
   
    protected $fillable=['title','content'];

}

=========================
*view:

1.resources\views\article\index.blade.php

@extends('layouts.app')

@section('content')

<section class="container">
    <a href="{{ url('article/create') }}" role="btn" class="btn btn-primary float-right">新增</a>
    <table class="table table-hover">
        @foreach($query as $var)
            <tr>
                <td>{{ $var->id }}</td>
                <td>{{ $var->title }}</td>
                <td><a href="{{ url('article/'.$var->id.'/edit') }}" role="btn" class="btn btn-warning">編輯</a></td>
                <td>
                    <form action="{{ url('article/'.$var->id) }}" method="post">
                        @csrf
                        @method("DELETE")
                        <input type="submit" role="btn" class="btn btn-danger" value="刪除" >
                    </form>
                </td>
            </tr>
        @endforeach
    </table>
</section>

@endsection

--------------------
2.resources\views\article\create.blade.php

@extends('layouts.app')

@section('content')

<section class="container">
    <h5>新增文章</h5>
    <form action="{{ url('article') }}" method="post">
        @csrf
        <div class="form-group">
            <label for="text1">主題:</label> <b class="text-danger">{{ $errors->first('title') }}</b>
            <input type="text" name="title" class="form-control" value="{{ old('title') }}" id="text1">
        </div>
        <div class="form-group">
            <label for="text2">內容:</label> <b class="text-danger">{{ $errors->first('content') }}</b>
            <textarea name="content" cols="30" rows="10" class="form-control" id="text2">{{ old('content') }}</textarea>
        </div>
        <input type="submit" value="送出" class="btn btn-primary">
    </form>
</section>

@endsection

--------------------
3.resources\views\article\edit.blade.php

@extends('layouts.app')

@section('content')

<section class="container">
    <h5>編輯文章</h5>
    <form action="{{ url('article/'.$query->id) }}" method="post">
        @csrf
        @method('PUT')
        <div class="form-group">
            <label for="text1">主題:</label> <b class="text-danger">{{ $errors->first('title') }}</b>
            <input type="text" name="title" class="form-control" value="{{(!$errors->has('title') and old('title')==null)?$query->title:old('title')}}" id="text1">
        </div>
        <div class="form-group">
            <label for="text2">內容:</label> <b class="text-danger">{{ $errors->first('content') }}</b>
            <textarea name="content" cols="30" rows="10" class="form-control" id="text2">{{(!$errors->has('content') and old('content')==null)?$query->content:old('content')}}</textarea>
        </div>
        <input type="submit" value="送出" class="btn btn-primary">
    </form>
</section>

@endsection

--------------------
4.resources\views\layouts\app.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        <!-- Authentication Links -->
                        @guest
                            <li class="nav-item">
                                <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                            </li>
                            <li class="nav-item">
                                @if (Route::has('register'))
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                @endif
                            </li>
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }} <span class="caret"></span>
                                </a>

                                <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

=========================
*Form Requests:

app\Http\Requests\ArticleRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ArticleRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
            'content' => 'required|min:3'
        ];
    }

    public function messages()
    {
        return [
            'required' => '不可為空白',
            'content.min' => '至少填寫3個字'
        ];
    }
}

=========================
*migration:

database\migrations\2019_01_05_033215_create_articles_table.php

<?php

use Illuminate\Support\Facades\Schema;
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',30);
            $table->text('content');
            $table->timestamps();
        });
    }

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

=========================
*seeder:

1.database\seeds\ArticleTableSeeder.php

<?php

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

use App\Article;

class ArticleTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('articles')->truncate();

        for ($i=0; $i < 10; $i++) {
            Article::create([
                'title'=>str_random(10),
                'content'=>str_random(255)
            ]);
        }
    }
}

---------------------
2.database\seeds\DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call('ArticleTableSeeder');
    }
}

=========================
*env:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=todolist
DB_USERNAME=root
DB_PASSWORD=



沒有留言:

張貼留言