程式CODE

顯示具有 laravel 標籤的文章。 顯示所有文章
顯示具有 laravel 標籤的文章。 顯示所有文章

2020年12月1日 星期二

laravel8安裝

 一、使用 composer 創建專案

composer create-project --prefer-dist laravel/laravel 專案名


裝完, .env 檔也建好了, key 也建好了。
如果沒有 key ,自行下指定  php artisan key:generate



二、變更目錄權限

sudo chmod 777 -R storage/ bootstrap/cache/
或是指定給 apache


三、修改  .env檔,
DB_DATABASE=資料庫名稱
DB_USERNAME=root
DB_PASSWORD=root密碼

建立資料庫

四、網頁目錄指定到 專案目錄/public 
apache 設定

<VirtualHost *:80>
       ServerName 專案網址
       DocumentRoot /var/www/html/專案名/public
       <Directory "/var/www/html/專案名/public/">
               Options -Indexes
               AllowOverride All
               Require all granted
       </Directory>
</VirtualHost>

五、成功連線畫面


六、使用者認證

https://tw511.com/a/01/13382.html

composer require laravel/jetstream

// Install Jetstream with the Livewire stack...
  • 如果你要 Livewire 和 Blade 一起使用,請執行:
php artisan jetstream:install livewire php artisan jetstream:install livewire --teams // Install Jetstream with the Inertia stack...
  • 如果你要 Inertia 與 Vue 一起使用,請執行:
php artisan jetstream:install inertia php artisan jetstream:install inertia --teams
最後執行
npm install && npm run dev



php aitisan migrate  //建立資料表


成功畫面




若有服務不要使用,可以在  ./config/fortity.php  中註解掉
    'features' => [
        Features::registration(),
        Features::resetPasswords(),
        // Features::emailVerification(),
        Features::updateProfileInformation(),
        Features::updatePasswords(),
        Features::twoFactorAuthentication(),
    ],


七、中文化
修改設定檔

2.1 設定
修改 config/app.php
...
'timezone' => 'Asia/Taipei',
'locale' => 'zh-TW',
'fallback_locale' => 'zh-TW',
...

2.2 語系
https://github.com/caouecs/Laravel-lang

下載 zh-TW 目錄及 zh_TW.json 至 resourses/lag/
//如果沒有顯示中文
php artisan config:clear
php artisan config:cache


八、laravel8 出現 controller not exit
https://medium.com/@litvinjuan/how-to-fix-target-class-does-not-exist-in-laravel-8-f9e28b79f8b4
請在  route 寫在完整路徑

2018年3月12日 星期一

laravel 5常用指令

建key
php artisan key:generate

建vendor
composer install

建立controller
php artisan make:controller PostsController --resource

安裝migration資料表
php artisan migrate:install

新建立model post的資料表
artisan make:migration {action}_{table}_table --create=posts
php artisan make:migration --create=students create_students_table

在posts表上,更動資料表
artisan make:migration {action}_{table}_table --table=posts

建立資料表
php artisan migrate (會先跑install)

建立model
artisan make:model Post

跑seeder
php artisan db:seed

建立policy
php artisan make:policy {PolicyName} --model={Model}
記得去註冊它
// app/Providers/AuthServiceProvider.php

2018年2月23日 星期五

為laravel auth 增加 圖形認證登入

參考自:https://phperzh.com/articles/1262

使用官方 auth下

1.安裝 mews/captcha
composer require mews/captcha

2.設定 /config/app.php
'providers' => [
    // ...
    Mews\Captcha\CaptchaServiceProvider::class,
]
'aliases' => [
    // ...
    'Captcha' => Mews\Captcha\Facades\Captcha::class,
]

3.產生設定檔 config/captcha.php
php artisan vendor:publish
可更改認證的字數或樣式
# 例如 flat 的樣式
...
    'flat'   => [
        'length'    => 5,  #認證的字數
        'width'     => 160,
        'height'    => 46,
        'quality'   => 90,
        'lines'     => 20,
        'bgImage'   => false,
        'bgColor'   => '#ecf2f4',
        'fontColors'=> ['#2c3e50', '#c0392b', '#16a085', '#c0392b', '#8e44ad', '#303f9f', '#f57c00', '#795548'],
        'contrast'  => -5,
    ],
...


4.修改登入頁面 /resources/views/auth/login.blade.php
在密碼的下方增加
...
<div class="form-group">
<label for="captcha" class="col-md-4 control-label">驗證碼</label>                 
    <div class="form-group">
<div class="col-md-3">
<input id="captcha"  class="form-control" type="captcha" name="captcha" value="{{ old('captcha')  }}" required>
             @if ($errors->has('captcha'))
                <span class="help-block">
                    <strong>驗證碼輸入錯誤</strong>
                </span>
            @endif
        </div>
<span class="col-md-1 refereshrecapcha">
        <a href="/login/refereshcapcha">{!! captcha_img('flat')  !!}</a>  #樣式 flat
</span>
    </div>
</div>
...

5.修改 /vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
要注意的是,因為修改的是 vendor 裡的檔案,有 clone 過來的,都要再去修改一次喔
...
protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|string',
        'password' => 'required|string',
        'captcha' => 'required|captcha',  #此行為新增
    ]);
}
...

6.對應路由
修改 /routes/web.php
新增
Route::get('/login/refereshcapcha', 'Auth\LoginController@refereshcapcha');

7.修改 LoginController
/app/Http/Controllers/Auth/LoginController.php
public function refereshcapcha()
{
     return captcha_img('flat');
}


2017年8月24日 星期四

laravel5.4版migrate出現的錯

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique (email))
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

出現上述錯誤
是因為mysql在5.7.7之前
只要改

「AppServiceProvider.php」 文件,在 function boot 内增加

use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringLength(191);
}

即可

https://news.laravel-china.org/posts/544

2017年7月25日 星期二

laravel helper function 輔助方法

asset('js/jquery.min.js');
從public開始找絕對路徑

url('/posts')


route('命名路由',參數)....route('命名路由',[參數,參數2])

2017年1月4日 星期三

建立自己的package

參考:
http://oomusou.io/laravel/laravel-package-hello-world/
https://rivsen.github.io/post/how-to-publish-package-to-packagist-using-github-and-composer-step-by-step

一、建立資料夾
專案根目錄 / packages / github的帳號 / package名稱 / src



















二、在packages 目錄下,新增composer.json


















composer.json


{
    "name": "wangchifu/test_page",
    "description": "this is a test for composer.",
    "license": "MIT",
    "authors": [
        {
          "name": "wangchifu",
          "email": "wangchifu@gmail.com"
        }
    ],
    "autoload": {
          "Wangchifu\\Test_page\\": "src/"
    },
    "require": {}
}


三、修改本地專案下的composer.json


...
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "Wangchifu\\Test_package\\": "packages/wangchifu/test_package/src/"
        }
    },
...


四、

2016年12月22日 星期四

laravel 5.3 自訂css及funcion,自訂參數

一、css放置在 ./public/css 下
<link rel="stylesheet" href="{{ asset('css/chc_sfs.css') }}">

二、自訂公用函式放在 ./app 下,再 composer.json裡新增
http://www.techigniter.in/blogs/tutorials/how-to-create-helpers-file-in-laravel-5/

請參考這個
http://www.jianshu.com/p/d11d49d166ab

1.先在 ./app 下建一個資料夾,如 chcsfs_fun,在裡面建function(helper)
接著,到根目錄下 ./composer.json 新增
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "files": [
                "app/chcsfs_fun/my_fun.php"
        ]
    },

2.到根目錄執行

composer dump-autoload

3.即可執行此檔案內的方法


三.自訂常數
在 ./env 可新增項目
...
PUSHER_SECRET=
DEFAULT_PASSWORD=demo1234
...

使用 env("DEFAULT_PASSWORD","預設值"),即可取得

或是在 ./config/app.php 中

...
    'name' => '學務系統',
    'sex' => '男',
...

使用 config("app.sex","預設值"),即可取得

或是新增一個檔案在 ./config裡,如 ./config/constants.php
內容為:
<?php
return array(

    'admin_email' =>'mail@shabeebk.com',
    'admin_name' =>'Admin',
);

爾後要取用,即可用
echo  Config::get('constants.admin_email');

echo  config('constants.admin_email');

2016年12月14日 星期三

laravel5.3 form class 的使用

一、5.3版已經沒有form class了,要額外安裝
sudo composer require "laravelcollective/html":"^5.3.0"

然後在 ./config/app.php
  'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
  ],


//還有


  'aliases' => [
    // ...
      'Form' => Collective\Html\FormFacade::class,
      'Html' => Collective\Html\HtmlFacade::class,
    // ...
  ],

如此即可使用
可參考
https://laravelcollective.com/docs/5.3/html


二、各表單元件使用
{{ Form::open(['url' => 'foo/bar',"method"=>"put"]) }}//,不寫就是預設 post
    //
{{ Form::close() }}


echo Form::open(['route' => 'route.name'])

echo Form::open(['action' => 'Controller@method'])

帶參數
echo Form::open(['route' => ['route.name', $user->id]])
echo Form::open(['action' => ['Controller@method', $user->id]])


echo Form::open(['url' => 'foo/bar', 'files' => true])

2016年12月7日 星期三

laravel 5.3 想辦法變成multi版,利用middlewaare

一、修改 .env
增加,0為單機版;1為multi版

MULTI_SERVER=1


二、新增一個 middleware
php artisan make:middleware MultiMiddleware

修改它
...
    public function handle($request, Closure $next)
    {
      if(!isset($_SESSION)) session_start();
      if(env('MULTI_SERVER')=='0') $_SESSION['schoolDB'] = env('DB_DATABASE', 'forge');
      if(env('MULTI_SERVER')=='1'){
        if(empty($_SESSION['schoolDB'])){
          $_SESSION['schoolDB']="";
          return redirect('school_list');
        }
      }
      return $next($request);
    }
}

...

註冊此middleware
在 ./app/Http/下修改kernel.php,增加一個multi的類別
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
        'multi' => \App\Http\Middleware\MultiMiddleware::class,
    ];

三、修改 ./config/database.php
//第1行加入
<?php
if(!isset($_SESSION)) session_start();
$schoolDB = $_SESSION['schoolDB'];
...

//約58行處,改成以下
...
'database' => $schoolDB,
...

四、做一個選擇學校的 route 及 view
route
修改web.php
//在根目錄下,用multi這個middleware驗證資料庫
Route::get('/', function () {
    return view ('welcome');
})->middleware(multi::class);

//或是用group,底下的route都要這個驗證
Route::group(['middleware' => 'multi'],function(){
  Route::get('/admin', function () {
      ...
  });
});

//選擇學校的route
Route::get('school_list',function(){
  return view('school_list');
});

//處理該校的資料庫
Route::get('school/{schoolDB}',function($schoolDB){
  if(!isset($_SESSION)) session_start();
  $_SESSION['schoolDB'] = $schoolDB;
  return redirect('/');
});

view
新增一個 school_list.blade.php





















每個連結到  /school/074xxx

laravel5.3 開啟內建auth使用者認證

一、建立資料庫
請參考之前文章,把資料庫及資料表users建立起來
users資料表在 ./database/migrations/2014_10_12_000000_create_users_table.php中設定

http://etplayinfo.blogspot.tw/2016/11/laravel53_29.html

自行在users表中再新一個 admin 的欄位 type 是 tinyint ,若為管理者,值為 1

二、切至laravel網站根目錄
php artisan make:auth
會產生多個 view 在 ./resources/views/auth


三、在 welcaom.blade.php中,多了以下


四、立即註冊登入






五、利用 middleware設計具管理身份

1.先建立 AdminMiddleware 切到 laravel 根目錄
php artisan make:middleware AdminMiddleware

2.修改 AdminMiddleware
在 ./app/Http/Middleware/ 下,把 RedirectfAuthenticated.php 內容複製到 AdminMiddleware.php 中,改類別名為 AdminMiddleware
略為修改為以下內容
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (Auth::guard($guard)->check() && Auth::user()->admin == 1) { 
//若users資料表內的admin欄為1,則下一個request,否則返回 / 
            return $next($request);
        }else{
            return redirect('/');
        }


    }
}

由以上得知,在往後要認證註冊:
Auth::guard($guard)->check()


要登入認證的controller,只要加入建構函式
     */
     public function __construct()
     {
         $this->middleware('auth');
     }
//
//except除此之外,都要用auth認證
//$this->middleware('auth')->except();
//or 只用
//$this->middleware('auth')->only();

要認證管理者登入:
if (Auth::guard($guard)->check() && Auth::user()->admin == 1) 


六、在需要管理者的頁面新增route
如:url/admin
Route::group(['middleware' => 'admin'],function(){
  Route::get('/admin', function () {
      echo "你是管理者";
  });
});


七、啟用 AdminMiddleware.php
在 ./app/Http/Kernel.php 中,增加以下 ...'admin'....這行,是copy 'guest' 這行再修改來的

protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
    ];

八、改用username登錄,而不是email
https://kjamesy.london/work/laravel-53-auth-allow-username-and-email

1.先在user資料表多一個username欄位

2.到 ./resources/views/auth/login.blade.php中,修改原  email欄位:
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
    <label for="email" class="col-md-4 control-label">E-Mail Address</label>
    <div class="col-md-6">
        <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
             @if ($errors->has('email'))
               <span class="help-block">
                 <strong>{{ $errors->first('email') }}</strong>
             </span>
        @endif
    </div>
</div>
成:

<div class="form-group{{ $errors->has('username') ? ' has-error' : '' }}">
    <label for="username" class="col-md-4 control-label">Username or Email</label>
    <div class="col-md-6">
        <input id="username" type="text" class="form-control" name="username" value="{{ old('username') }}" autofocus>
        @if ($errors->has('username'))
            <span class="help-block">
                <strong>{{ $errors->first('username') }}</strong>
            </span>
        @endif
    </div>
</div>

3.在 ./app/Http/Controllers/Auth/LoginController.php
新增一個 function
public function username()
{
    return 'username';
}

2016年11月29日 星期二

laravel5.3 models操作

一、可使用 migration建資料表,或其他方式

二、填入資料

三、建立model
  在 ./app 下建一個 Post.php,內容如下:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
}

特別注意的是,這裡首字大寫,單數,而就會自動抓資料表為小寫,複數
除非

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
  protected $table = "posts ";  ##指定資料表名稱
  public $timestamps = false;  ##取消時間戳記,記得要把遷移檔中的刪掉
}


或是下指令:

php artisan make:model Post

四、在 ./routes/web.php
Route::get('test2', function () {
    $test=App\Post::where('title','=','test2')->first();
echo $test->id;
});

同樣程式,若寫在controller上,就記得要 use App\該model

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class TestController extends Controller
{
    public function index()
    {
      $test=Post::where('title','=','test2')->first();
      echo $test->title;
    }


九、可用的方法
$test=App\Post::first();  ##查第一筆資料
echo $test->title;  ##查欄位 title
$test=App\Post::find(1);  ##查第一筆資料
echo $test->title;  ##查欄位 title

$test=App\Post::where('title','=','test2')->first();  ##where
echo $test->id;  ##查欄位 id
$test=App\Post::all();  ##全部

十、eloquent orm操作
在controller裡
新增1:

use App\Post;

$post = new Post;
$post->title = $request->input('title');
$post->save();

新增2(靜態):
Post::create($request->all());


取新增的id:
$insertedId = $post->id;

更新1:
$post = Post::find(24);
$post->title = $request->input('title');
$post->save();


更新2(靜態):
$post = Post::find($id);
$post->update($request->all());


刪除1:
$user = Post::find(1);
$user->delete();

刪除,依where
$affectedRows = Post::where('votes', '>', 100)->delete();


laravel5.3 使用migrations資料庫操作

一、建立資料庫名稱
  使用phpMyAdmin建一個資料庫""chcsfs,或是下指令

# mysql -u root -p
Enter password:

mysql> CREATE DATABASE 'chcsfs';
Query OK, 1 row affected (0.00 sec)


二、編輯 .env
  不要直接寫在 ./config/database.php,應寫在  .env
...
DB_CONNECTION=mysql
DB_HOST=localhost  //這裡切記要用這個
DB_PORT=3306
DB_DATABASE=chcsfs
DB_USERNAME=root
DB_PASSWORD=密碼
...



三、使用migrations建立migration表
  若storage資料夾沒有設定777,可用sudo

php artisan migrate:install


四、migration指令

##建立遷移檔
php artisan make:migration create_posts_table

##順便建schema建一個資料表名稱為 posts
php artisan make:migration create_posts_table2 --create=posts

##順便建schema改資料表名稱為 posts
php artisan make:migration create_posts_table2 --table=posts

##右邊是4版前的指令,已不支援  php artisan migrate:make create_posts_table

##目前遷移檔的狀況
php artisan migrate:status

##會執行遷移檔中的 up()方法,依遷移檔建立、修改資料表
php artisan migrate

##會執行遷移檔中的 down()方法,用以還原或移除遷移檔的資料表
php artisan migrate:rollback



五、migrations遷移檔中schema的指令

  Schema::create()  ##建立資料表
  Schema::rename($from,$to)  ##改資料表名稱
  Schema::talbe($from,$to)  ##新增、修改該資表內的欄位

如:
https://laravel.com/docs/4.2/schema

public function up()
{
    ##建立資料表
    Schema::create('posts', function($table){
        $table->increments('id')->index();  ##並設定index
        $table->boolean('confirmed');
        $table->unsignedInteger('page_view');//正整數
        $table->integer('page_view')->unsigned();//正整數2
        $table->integer('votes');
        $table->string('title');
        $table->string('content');
        $table->text('description');
        $table->date('created_at');
        $table->datetime('created_at');
        $table->timestamps();  ##建立時間戳記
    });

    ##在該資料表內,新增、修改、刪除欄位
    Schema::table('posts', function($table){
        $table-->dropColumn('欄位');  ##刪除欄位
        $table->timestamps();
    });
}

public function down()
{
  Schema::drop('資料表')
  Schema::dropIfExists('資料表')
}



2016年11月23日 星期三

laravel5.3-view

一、放置在 ./resources/views 放置模板,./resources/views/layouts 放置主模,
  ./resources/views/layouts/partials 放置區塊

二、可新增目錄分類

三、名稱為   name.blade.php

四、用 return view('樣板名稱');中間資料夾用 . 分隔

五、blade使用

  @extends 延伸自哪個模板
  @yield 主模板中,等套入的區域,後面@yield("命名");
  @include 保含哪一個模板

例:在views版下放置一個 default.blade.php 預設模板
內容如下:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>@yield('title')</title>
</head>
<body>
    @include("layouts.partials.sidebar")
    <div class="container">
        @yield('content')
    </div>
    @include('layouts.partials.footer')
</body>
</html>

日後新增模板,即可:
@extends('default')
@section('title','標題')
@section('content')
    <h1>測試</h1>
    <div>新增模板</div>
@endsection

六、帶參數進模板
./routes/web.php

Route::get('teacher_base', function () {
    $data=['name'=>'Tom'];
    return view ('teacher_base.index',$data);
});

或是在view()下用with()方法
Route::get('/', function () { return view ('welcome')->with('hello', '大家好~~'); });
然後在welcome.blade.php
Laravel{{$hello}}
./resources/views/模板.blade.php

<div>新增教師 {{$name}}</div>

laravel5.3中介層

https://wastemobile.gitbooks.io/laravel-5-chinese-document/content/middleware.html

 Laravel 框架已經內建一些中介層,包括維護、身份驗證、CSRF 保護,等等。所有的中介層都位於 app/Http/Middleware 目錄內

一、建立一個中介層

php artisan make:middleware OldMiddleware 

此指令將會 在 app/Http/Middleware 目錄內建立一個名稱為 OldMiddleware 的類別

//以下中介層,$request->age不大於200即轉走!

<?php

namespace App\Http\Middleware;

use Closure;

class CheckAge
{
    /**
     * Run the request filter.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->age <= 200) {
            return redirect('home');
        }

        return $next($request);
    }

}

二、有些事可以在haddle之前先做 之前

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}



之後
<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}


三、註冊
全域:只要將中介層的類別加入到 app/Http/Kernel.php 的 $middleware 屬性清單列表中。
指派給路由:
1.先在Kernel.php指定key
如:
protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

你即可在設定路由時使用
Route::get('admin/profile', function () {
    //
})->middleware('auth');

2016年11月21日 星期一

laravel5.3-Routing

route寫在 ./routes/web.php


一、基本route

Route::get('foo', function () {
    return 'Hello World';
});















二、所有的method (http verbs請求)

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

put,patch,delete,options請求用
<input type="hidden" name="_method" value="PUT">


{{ method_field('PATCH') }}


範例:

編輯 ./routes/web.php
Route::get('test','TestController@index');

新增controller
php artisan make:controller TestController --resource

編輯 ./app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        echo "測試一下!";
    }
...














三、若有多個method
Route::match(['get', 'post'], '/', function () { // });

四、若代表全部method
Route::any('foo', function () { // });

五、防範CSRF攻擊
會自動驗證token在post,put,delete請求

<form method="POST" action="/profile">
     <input type="hidden" value="'.csrf_token().'" name="_token">
    ...
</form>


https://zh.wikipedia.org/wiki/%E8%B7%A8%E7%AB%99%E8%AF%B7%E6%B1%82%E4%BC%AA%E9%80%A0





{{ csrf_field() }}




<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">

或在blade樣板
<input type="hidden" name="_token" value="{{ csrf_token() }}">


六、帶參數
//單一參數
Route::get('user/{id}', function ($id) {
    return 'User '.$id;
});

//多參數
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
    //
});


//可預設參數,此時name可有可無
Route::get('user/{name?}', function ($name = 'John') {
    return $name;
});


//限制參數
Route::get('user/{id}', function ($id) {
    return $name;
})->where('id','[0-9]+');


//如果大批where對id,以下所有route的id,都循[0-9]+的正規
Route::pattern('id','[0-9]+');


七、命名路由
Route::get('user/profile所命名', function () {
    //
})->name('frofile');

Route::get('user/profile', 'UserController@showProfile')->name('profile');


//尚未了解用法
$url = route('profile', ['id' => 1]);


//5.2版前的用法
Route::get('user/profile', ['as' => 'user.profile', 'uses' => 'TestController@index']);

八、群組
使用 Route::group
列如:
Route::group(['middleware' =>'{auth}'],function(){
  Route::get('/',function(){
    //程式碼
  });
  Route::get('user/profile',function(){
    //程式碼
  });
);
});


九、前綴
URI路徑就有一個前綴
Route::group(['prefix' => 'admin'], function () {
    Route::get('users', function ()    {
        // Matches The "/admin/users" URL
    });
});

2016年11月16日 星期三

laravel5.3設定

1.設定時區
修改 ./config/app.php
'timezone' => 'Asia/Taipei'

2.設定mysql(以下不建議,最好寫在 .env下)
修改 ./config/database.php
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', '資料庫名'),
            'username' => env('DB_USERNAME', '使用者'),
            'password' => env('DB_PASSWORD', '密碼'),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ],

3.設定key
php artisan key:generate

2016年11月1日 星期二

laravel5.3安裝備忘(安裝於ubuntu16.04)

一、必要安裝
安裝等等要解壓的工具
sudo apt-get install unzip zip

安裝lamp
sudo apt-get install lamp-server^

安裝php擴充
sudo apt-get install php7.0-cli  php7.0-json php7.0-mcrypt php7.0-mbstring php7.0-gd php7.0-xml(即php5-dom)


二、下載安裝composer
下載
wget -c https://getcomposer.org/composer.phar

可執行
chmod +x composer.phar

移到/usr/local/bin,改名composer
sudo mv composer.phar /usr/local/bin/composer

composer基本指令
測試看看
composer

版本
composer -V

升級
composer self-update

是否有效
composer validate

三、用composer於html下安裝laravel,放置在your_website
不得用root使用者
composer create-project laravel/laravel --prefer-dist 安裝目錄your_website 成功後,出現:
php artisan key:generate
Application key [base64:gS7Fs2tXdjW3UVmAuO/+YRvCDrHmgaqU84iPCIgJ368=] set successfully.

四、
加入apache虛擬主機
sudo vim /etc/apache2/sites-available/laravel.conf 

寫入:
<VirtualHost *:80>
        ServerName chcsfs.localhost.edu.tw
        DocumentRoot /var/www/html/chcsfs/public
      <Directory /var/www/html/chcsfs>
        AllowOverride All
        </Directory>
</VirtualHost>


重啟apache service apache2 reload

五、更改特定目錄擁有者為www-data,及777
sudo chown -R www-data: ./storage ./bootstrap/cache
sudo chmod -R 777 ./storage ./bootstrap/cache

六、隱藏 index.php,啟用apache2 rewrite模組 sudo a2enmod rewrite
sudo service apache2 restart