Laravel中常用的命令和方法(一)

1.創建數據表遷移文件

php artisan make:migration create_user_table

2.在創建的遷移文件中設置表屬性,字段等。

public function up()
    {
        Schema::create('blog_article',function(Blueprint $table){
            $table->increments('article_id')->index();
            $table->integer('author_id')->index();
            $table->integer('article_pid');
            $table->timestamp('created_at');
            $table->string('article_title');
            $table->text('content');
        });
    }

3.創建數據表

php artisan migrate

4.創建控制器

php artisan make:controller UserController

這條命令會在app/Http/Controller下創建UserController.php文件
如果在別的命名空間下創建控制文件,可在命令中帶命名空間

php artisan make:controller Admin\UserController

5.創建RESTful資源型控制器

php artisan make:controller Admin\UserController --resource

這條命令會在Http/Admin下創建控制器UserController.php ,并且控制器中帶有7個方法。

    public function index()
        {
            //

        }


        public function create()
        {
            //

        }


        public function store(Request $request)
        {


        }


        public function show($id)
        {
            //
        }


        public function edit($id)
        {

        }


        public function update(Request $request, $id)
        {


        }


        public function destroy($id)
        {

        }

使用命令可以查看這幾個方法對應的路由以及作用

php artisan route:list

6.查看php artisan 命令

php artisan

列表顯示laravel的各種命令。

    PS G:\www\blog> php artisan
    Laravel Framework version 5.2.45

    Usage:
      command [options] [arguments]

    Options:
      -h, --help            Display this help message
      -q, --quiet           Do not output any message
      -V, --version         Display this application version
          --ansi            Force ANSI output
          --no-ansi         Disable ANSI output
      -n, --no-interaction  Do not ask any interactive question
          --env[=ENV]       The environment the command should run under.
      -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

    Available commands:
      clear-compiled      Remove the compiled class file
      down                Put the application into maintenance mode
      env                 Display the current framework environment
      help                Displays help for a command
      list                Lists commands
      migrate             Run the database migrations
      optimize            Optimize the framework for better performance
      serve               Serve the application on the PHP development server
      tinker              Interact with your application
      up                  Bring the application out of maintenance mode
     app
      app:name            Set the application namespace
     auth
      auth:clear-resets   Flush expired password reset tokens
     cache
      cache:clear         Flush the application cache
      cache:table         Create a migration for the cache database table
     config
      config:cache        Create a cache file for faster configuration loading
      config:clear        Remove the configuration cache file
     db
      db:seed             Seed the database with records
     event
      event:generate      Generate the missing events and listeners based on registration
     key
      key:generate        Set the application key
     make
      make:auth           Scaffold basic login and registration views and routes
      make:console        Create a new Artisan command
      make:controller     Create a new controller class
      make:event          Create a new event class
      make:job            Create a new job class
      make:listener       Create a new event listener class
      make:middleware     Create a new middleware class
      make:migration      Create a new migration file
      make:model          Create a new Eloquent model class
      make:policy         Create a new policy class
      make:provider       Create a new service provider class
      make:request        Create a new form request class
      make:seeder         Create a new seeder class
      make:test           Create a new test class
     migrate
      migrate:install     Create the migration repository
      migrate:refresh     Reset and re-run all migrations
      migrate:reset       Rollback all database migrations
      migrate:rollback    Rollback the last database migration
      migrate:status      Show the status of each migration
     queue
      queue:failed        List all of the failed queue jobs
      queue:failed-table  Create a migration for the failed queue jobs database table
      queue:flush         Flush all of the failed queue jobs
      queue:forget        Delete a failed queue job
      queue:listen        Listen to a given queue
      queue:restart       Restart queue worker daemons after their current job
      queue:retry         Retry a failed queue job
      queue:table         Create a migration for the queue jobs database table
      queue:work          Process the next job on a queue
     route
      route:cache         Create a route cache file for faster route registration
      route:clear         Remove the route cache file
      route:list          List all registered routes
     schedule
      schedule:run        Run the scheduled commands
     session
      session:table       Create a migration for the session database table
     vendor
      vendor:publish      Publish any publishable assets from vendor packages
     view
      view:clear          Clear all compiled view files

7.創建模型

php artisan make:model User

這條命令會在app下創建一個模型文件User.php

php artisan make:model Http\Model\User

這條命令會在app/Http/Model下創建模型文件User.php

8.安裝laravel

composer create_project larvel/laravel --prefer-dist

9.laravel/laravel和laravel/framework

laravel/laravel:laravel框架的示例程序,已經包含laravel框架源代碼和其他的外部庫
laravel/framework:僅僅Laravel框架的源代碼

10.laravel 5.2php版本要求

  • PHP >= 5.5.9
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension

11. 生成每臺電腦唯一的key

php artisan key generate

12.laravel路由有幾種

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

13響應多個路由

    Route::match(['get', 'post'], '/', function () {
        //
    });

    Route::any('foo', function () {
        //
    });

14.路由傳參(必傳)

    Route::get('/shenhe/{art_id}','ArticleController@shenhe');
    //文章上架
    Route::get('/up/{art_id}','ArticleController@up');
    //文章下架
    Route::get('/stop/{art_id}','ArticleController@stop');

注意: 路由參數不能包含 - 字符。請用下劃線 (_) 替換。

15.路由傳參(可選)

    Route::get('user/{name?}', function ($name = null) {
        return $name;
    });

    Route::get('user/{name?}', function ($name = 'John') {
        return $name;
    });

16.路由命名

    Route::get('user/profile', [
    'as' => 'profile', 'uses' => 'UserController@showProfile'
]);

這個路由名稱為profile

17.路由群組

    Route::group(['middleware'=>['web'],'namespace'=>'Home'],function(){
        Route::get('/', 'IndexController@index');
        Route::get('/article/{art_id}', 'ArticleController@index');
        Route::get('/cate/{cate_id}', 'ArticleController@cate');

    });

18.對命名路由生成urls

    $url = route('profile');

    $redirect = redirect()->route('profile');

19.路由前綴

    Route::group(['middleware'=>['web'],'prefix'=>'admin','namespace'=>'Admin'],function(){
    //后臺登錄
    Route::any('/login','LoginController@login');

    //驗證碼路由
    Route::get('/code','LoginController@code');
});

20.什么是CSRF保護

Laravel 會自動生成一個 CSRF token 給每個用戶的 Session。該token用來驗證用戶是否為實際發出請求的用戶??梢允褂?csrf_field 輔助函數來生成一個包含 CSRF token 的

21.模板中使用csrf保護

    {{ csrf_field() }}

22.ajax在laravel框架中的使用(刪除)

    /*文章-刪除*/
        function article_del(obj,id){
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('input[name="_token"]').val()
                }
            });
            layer.confirm('確認要刪除嗎?',function(index){
                $.ajax({
                    type: 'delete',
                    url: "{{url('admin/article')}}"+"/"+id,
                    success: function(data){
                        if(data.status==1){
                            $(obj).parents("tr").remove();
                           layer.msg('已刪除!',{icon:1,time:1000});
                        }else{
                            layer.msg('已刪除!',{icon:5,time:1000});
                        }
                    }
                });
            });
        }

23.ajax在laravel框架中的使用(新增)

    $("#form-article-add").validate({

                onkeyup:false,
                focusCleanup:true,
                success:"valid",
                submitHandler:function(form){
                    $(form).ajaxSubmit({
                        url:"{{url('admin/article')}}",
                        type:'post',
                        success:function(data){

                            if(data.status==1){
                                layer.msg(data.msg,{icon:6},function(){
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.window.location.reload();
                                    parent.layer.close(index);
                                });
                            }else if(data.status==0){
                                layer.msg(data.msg,{icon:5});
                            }
                        }
                    });
                }
            });

24.ajax在laravel框架中的使用(編輯)

$("#form-article-edit").validate({

                onkeyup:false,
                focusCleanup:true,
                success:"valid",
                submitHandler:function(form){
                    $(form).ajaxSubmit({
                        url:"{{url('admin/article/'.$data->art_id)}}",
                        type:'put',
                        success:function(data){
                            if(data.status==1){
                                layer.msg(data.msg,{icon:6},function(){
                                    var index = parent.layer.getFrameIndex(window.name);
                                    parent.window.location.reload();
                                    parent.layer.close(index);
                                });
                            }else if(data.status==0){
                                layer.msg(data.msg,{icon:5});
                            }
                        }
                    });
                }
            });

25.ajax在laravel框架中的使用(get方法)

function changeOrder(cate_id,obj){
            $.ajax({
                url:"{{url('admin/changeOrder').'/'}}"+cate_id+'/cate_order/'+obj.value,
                type:'get',
                success:function(data){
                    if(data.status==1){
                        layer.msg(data.msg,{icon:6});
                    }else{
                        layer.msg(data.msg,{icon:5});
                    }

                }
            });
        }

26,不用ajax,怎么在表單中直接提交修改刪除這些操作?

    <form action="/foo/bar" method="POST">
        <input type="hidden" name="_method" value="PUT">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
    </form>

或者:

    {{ method_field('PUT') }}

27.中間件

HTTP 中間件提供了一個方便的機制來過濾進入應用程序的 HTTP 請求,例如,Auth 中間件驗證用戶的身份,如果用戶未通過身份驗證,中間件將會把用戶導向登錄頁面,反之,當用戶通過了身份驗證,中間件將會通過此請求并接著往下執行。

28.創建中間件

    php artisan make:middleware AdminLogin

新創建的中間件命名空間及方法

    namespace App\Http\Middleware;

use Closure;

class AdminLogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!session('user')){
            return redirect('admin/login');
        }
        return $next($request);
    }
}

29.注冊中間件

在app/Http/Kernel.php的$middleware屬性中添加中間件

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

最后一個,就是剛才創建的中間件

30.指派中間件

    Route::group(['middleware'=>['web','admin.login'],'prefix'=>'admin','namespace'=>'Admin'],function(){
    //后臺首頁
    Route::get('/index','IndexController@index');
    //退出登錄
    Route::get('/quit','LoginController@quit');
    //修改密碼
    Route::any('/pass','IndexController@pass');
    //測試方法
    Route::any('/test','IndexController@test');
    //文章分類
    Route::resource('/category','CategoryController');
    //文章管理
    Route::resource('/article','ArticleController');
    //修改分類排序
    Route::get('/changeOrder/{cate_id}/cate_order/{cate_order}','CategoryController@changeOrder');
    //上傳圖片
    Route::any('/upload','CommonController@upload');
    //文章審核
    Route::get('/shenhe/{art_id}','ArticleController@shenhe');
    //文章上架
    Route::get('/up/{art_id}','ArticleController@up');
    //文章下架
    Route::get('/stop/{art_id}','ArticleController@stop');
    //友情鏈接
    Route::resource('/links','LinksController');
    //修改友情鏈接排序
    Route::get('/changeLinkOrder/{link_id}/link_order/{link_order}','LinksController@changeOrder');
    //導航
    Route::resource('/navs','NavsController');
    //修改導航排序
    Route::get('/changeNavOrder/{nav_id}/nav_order/{nav_order}','NavsController@changeOrder');
    //網站配置
    Route::resource('/conf','ConfigController');
    //修改配置順序
    Route::get('/changeConfOrder/{conf_id}/conf_order/{conf_order}','ConfigController@changeOrder');
    Route::post('/multi_edit','ConfigController@multiEdit');
    Route::get('/gen_conf','ConfigController@putFile');
});

以上路由都需要在登錄的情況下再能執行

31.路由緩存

    php artisan route:cache

清除緩存路由

    php artisan route:clear

32.獲取URL地址

    // 不包含請求字串
    $url = $request->url();

    // 包含請求字串(請求字串如:`?id=2`)
    $url = $request->fullUrl();

33.獲取(請求的方法)

    $method = $request->method();

34.判斷http動作

    if ($request->isMethod('post')) {
        //
    }

35.獲取表單提交數據(Innput類)

    $input=Input::except('_token');
    $input=Input::all();

36.獲取表單提交數據(Request)

    $name = $request->input('name');

或者

    $name = $request->name;

37.確認是否有輸入值

    if ($request->has('name')) {
    //
    }

38.獲取輸入數據(Request)

    $input = $request->all();
    $input = $request->except('credit_card');

39.判斷是否有文件上傳

    if ($request->hasFile('photo')) {
    //
    }

40.獲取上傳文件

    $file = $request->file('photo');
    $file=Input::file('file');

41.判斷上傳文件是否有效

    if($file->isValid()){

        }

42.獲取上傳文件的擴展名

     $entension=$file->getClientOriginalExtension();

43.重定向

    Route::get('dashboard', function () {
        return redirect('home/dashboard');
    });

44.重定向至控制器行為

    return redirect()->action('HomeController@index');

45.使用視圖

    return view('admin.profile');

46.判斷視圖是否存在

    if (view()->exists('emails.customer')) {
        //
    }

47.向視圖傳數據

    return view('greetings', ['name' => 'Victoria']);


    $data=Links::find($id);
     return view('admin.links.edit',compact('data'));

48.向視圖傳數據

    $category=new Category();
    $data=$category->getTree();
    return view('admin.category.index')->with('data',$data);

49.數據共享

    class CommonController extends Controller
    {
        public function __construct(){
            $nav= Category::orderBy('cate_order','asc')->get();
           View::share('nav',$nav);
        }
    }

注意:這個類是個基類,它共享的數據在它的派生類對應的視圖中實現。

50.Blade模板

Blade 是 Laravel 所提供的一個簡單且強大的模板引擎。相較于其它知名的 PHP 模板引擎,Blade 并不會限制你必須得在視圖中使用 PHP 代碼。所有 Blade 視圖都會被編譯緩存成普通的 PHP 代碼,一直到它們被更改為止。這代表 Blade 基本不會對你的應用程序生成負擔。

Blade 視圖文件使用 .blade.php 做為擴展名,通常保存于 resources/views 文件夾內。

51.模板繼承

定義父模板,公共部分留在這里,需要改變的使用yield

    <html>
    <head>
        <title>應用程序名稱 - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            這是主要的側邊欄。
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
    </html>

在子頁面中繼承

    @extends('layouts.master')

    @section('title', '頁面標題')

    @section('sidebar')
        @parent

        <p>這邊會附加在主要的側邊欄。</p>
    @endsection

    @section('content')
        <p>這是我的主要內容。</p>
    @endsection

@parent命令是添加而不是覆蓋

52.在子模板中改變父級模板內容

首先在父級模板中

    @section('title')
    <title>國民的博客</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    @show

在子模板中直接更換這個部分。如果子模板中不寫這個section,那么模板會默認繼承。

53.blade數據顯示

{{ $name }}.
目前的 UNIX 時間戳為 {{ time() }}。

54.數據存在時輸出

    {{ $name or 'Default' }}

類似于三元操作符

55.顯示未轉義數據

 {!! $name !!}.

56.if表達式

    @if (count($records) === 1)
        我有一條記錄!
    @elseif (count($records) > 1)
        我有多條記錄!
    @else
        我沒有任何記錄!
    @endif

57.循環

    @for ($i = 0; $i < 10; $i++)
        目前的值為 {{ $i }}
    @endfor

    @foreach ($users as $user)
        <p>此用戶為 {{ $user->id }}</p>
    @endforeach

    @forelse ($users as $user)
        <li>{{ $user->name }}</li>
    @empty
        <p>沒有用戶</p>
    @endforelse

    @while (true)
        <p>我永遠都在跑循環。</p>
    @endwhile

58.目錄結構

  • app 目錄,如你所料,這里面包含應用程序的核心代碼。我們之后將很快對這個目錄的細節進行深入探討。

  • bootstrap 目錄包含了幾個框架啟動跟自動加載設置的文件。以及在 cache 文件夾中包含著一些框架在啟動性能優化時所生成的文件。

  • config 目錄,顧名思義,包含所有應用程序的配置文件。

  • database 目錄包含數據庫遷移與數據填充文件。如果你愿意的話,你也可以在此文件夾存放 SQLite 數據庫。

  • public 目錄包含了前端控制器和資源文件(圖片、JavaScript、CSS,等等)。

  • resources 目錄包含了視圖、原始的資源文件 (LESS、SASS、CoffeeScript) ,以及語言包。

  • storage 目錄包含編譯后的 Blade 模板、基于文件的 session、文件緩存和其它框架生成的文件。此文件夾分格成 app、framework,及 logs 目錄。app 目錄可用于存儲應用程序使用的任何文件。framework 目錄被用于保存框架生成的文件及緩存。最后,logs 目錄包含了應用程序的日志文件。

  • tests 目錄包含自動化測試。這有一個現成的 PHPUnit 例子。

  • vendor 目錄包含你的 Composer 依賴模塊。

59.加密

$user->user_pass=Crypt::encrypt($input['password']);

60解密

$password=Crypt::decrypt($user->user_pass);

61.日志模式

'log' => 'daily'

laravel提供四種日志模式

  • single
  • daily
  • syslog
  • errorlog

62.全部分頁

$users = DB::table('users')->paginate(15);

63.上一頁、下一頁

$users = DB::table('users')->simplePaginate(15);

64.對Eloquent進行分頁

$users = User::where('votes', '>', 100)->paginate(15);

65.視圖中顯示分頁

{{ $users->links() }

66.表單驗證

    $rules=[
        'oldpass'=>'required',
        'password'=>'required|between:6,20|confirmed',
    ];
    $messages=[
        'oldpass.required'=>'舊密碼不能為空',
        'password.required'=>'新密碼不能為空',
        'password.between'=>'新密碼在6-20位之間',
        'password.confirmed'=>'新密碼和確認密碼不一致',
    ];
    $validator=Validator::make($input,$rules,$messages);
    if($validator->passes()){
        //驗證通過,。。
    }else{
        $errors=$validator->errors()->all();
        echo json_encode($errors);
    }

67.查看特定字段的第一個錯誤消息

$messages = $validator->errors();

echo $messages->first('email');

68.判斷特定字段是否有錯誤消息

if ($messages->has('email')) {
    //
}

69.可用的驗證規則

  • accepted
    驗證字段值是否為 yes、on、1、或 true。這在確認「服務條款」是否同意時相當有用。
  • active_url
    驗證字段值是否為一個有效的網址,會通過 PHP 的 checkdnsrr 函數來驗證。
    alpha
    驗證字段值是否僅包含字母字符。
  • alpha_dash
    驗證字段值是否僅包含字母、數字、破折號( - )以及下劃線( _ )。
  • alpha_num
    驗證字段值是否僅包含字母、數字。
  • array
    驗證字段必須是一個 PHP array。

  • between:min,max
    驗證字段值的大小是否介于指定的 min 和 max 之間。字符串、數值或是文件大小的計算方式和 size 規則相同。

  • digits:value
    驗證字段值是否為 numeric 且長度為 value。

  • integer
    驗證字段值是否是整數。

  • numeric
    驗證字段值是否為數值。
    70.laravel支持的數據庫

  • MySQL

  • Postgres

  • SQLite

  • SQL Server

71.數據庫配置

在config/database.php頁面

    'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            //'prefix' => env('DB_PREFIX', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

72.數據庫讀寫分離

'mysql' => [
            'read' => [
                'host' => '192.168.1.1',
            ],
            'write' => [
                'host' => '196.168.1.2'
            ],
            'driver' => 'mysql',
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            //'prefix' => env('DB_PREFIX', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

73.原始SQL查找

$users = DB::select('select * from users where active = ?', [1]);

DB facade 提供類型的查找方法還有:update、insert、delete、statement。

74.使用命名綁定

$results = DB::select('select * from users where id = :id', ['id' => 1]);

75.insert

DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);

76.update

$affected = DB::update('update users set votes = 100 where name = ?', ['John']);

77.delete

$deleted = DB::delete('delete from users');

78.一般聲明

DB::statement('drop table users');

79.結果集中獲取所有數據列

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

80.從數據表中獲取單個列或者行

$user = DB::table('users')->where('name', 'John')->first();

echo $user->name;

81.獲取某個字段值

$email = DB::table('users')->where('name', 'John')->value('email');

82.獲取字段值列表

$titles = DB::table('roles')->pluck('title');

83.聚合

查詢構造器也提供了各種聚合方法,例如 count、max、min、avg、以及 sum。

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

84.select字句

$users = DB::table('users')->select('name', 'email as user_email')->get();

85.Left Join

$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

86.where 字句

$users = DB::table('users')->where('votes', '=', 100)->get();

上面查詢也可以寫成這樣

$users = DB::table('users')->where('votes', 100)->get();

87.where字句其他算法

$users = DB::table('users')
                ->where('votes', '>=', 100)
                ->get();

$users = DB::table('users')
                ->where('votes', '<>', 100)
                ->get();

$users = DB::table('users')
                ->where('name', 'like', 'T%')
                ->get();

88.orderBy排序

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->get();

89.獲取結果隨機排序

$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();

90.限制查找數量

$users = DB::table('users')->skip(10)->take(5)->get();

91.插入

DB::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);

92.更新

DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);

93.刪除

DB::table('users')->where('votes', '<', 100)->delete();

94.數據庫遷移事可用的字段類型


    命令  描述
    $table->bigIncrements('id');    遞增 ID(主鍵),相當于「UNSIGNED BIG INTEGER」型態。
    $table->bigInteger('votes');    相當于 BIGINT 型態。
    $table->binary('data'); 相當于 BLOB 型態。
    $table->boolean('confirmed');   相當于 BOOLEAN 型態。
    $table->char('name', 4);    相當于 CHAR 型態,并帶有長度。
    $table->date('created_at'); 相當于 DATE 型態。
    $table->dateTime('created_at'); 相當于 DATETIME 型態。
    $table->dateTimeTz('created_at');   DATETIME (with timezone) 帶時區形態
    $table->decimal('amount', 5, 2);    相當于 DECIMAL 型態,并帶有精度與基數。
    $table->double('column', 15, 8);    相當于 DOUBLE 型態,總共有 15 位數,在小數點后面有 8 位數。
    $table->enum('choices', ['foo', 'bar']);    相當于 ENUM 型態。
    $table->float('amount');    相當于 FLOAT 型態。
    $table->increments('id');   遞增的 ID (主鍵),使用相當于「UNSIGNED INTEGER」的型態。
    $table->integer('votes');   相當于 INTEGER 型態。
    $table->ipAddress('visitor');   相當于 IP 地址形態。
    $table->json('options');    相當于 JSON 型態。
    $table->jsonb('options');   相當于 JSONB 型態。
    $table->longText('description');    相當于 LONGTEXT 型態。
    $table->macAddress('device');   相當于 MAC 地址形態。
    $table->mediumInteger('numbers');   相當于 MEDIUMINT 型態。
    $table->mediumText('description');  相當于 MEDIUMTEXT 型態。
    $table->morphs('taggable'); 加入整數 taggable_id 與字符串 taggable_type。
    $table->nullableTimestamps();   與 timestamps() 相同,但允許為 NULL。
    $table->rememberToken();    加入 remember_token 并使用 VARCHAR(100) NULL。
    $table->smallInteger('votes');  相當于 SMALLINT 型態。
    $table->softDeletes();  加入 deleted_at 字段用于軟刪除操作。
    $table->string('email');    相當于 VARCHAR 型態。
    $table->string('name', 100);    相當于 VARCHAR 型態,并帶有長度。
    $table->text('description');    相當于 TEXT 型態。
    $table->time('sunrise');    相當于 TIME 型態。
    $table->timeTz('sunrise');  相當于 TIME (with timezone) 帶時區形態。
    $table->tinyInteger('numbers'); 相當于 TINYINT 型態。
    $table->timestamp('added_on');  相當于 TIMESTAMP 型態。
    $table->timestampTz('added_on');    相當于 TIMESTAMP (with timezone) 帶時區形態。
    $table->timestamps();   加入 created_at 和 updated_at 字段。
    $table->uuid('id'); 相當于 UUID 型態。

95.字段修飾

    ->first()   將此字段放置在數據表的「第一個」(僅限 MySQL)
    ->after('column')   將此字段放置在其它字段「之后」(僅限 MySQL)
    ->nullable()    此字段允許寫入 NULL 值
    ->default($value)   為此字段指定「默認」值
    ->unsigned()    設置 integer 字段為 UNSIGNED
    ->comment('my comment') 增加注釋

96.創建索引

$table->string('email')->unique();

或者

$table->unique('email');

97.可用的索引類型

    $table->primary('id');  加入主鍵。
    $table->primary(['first', 'last']); 加入復合鍵。
    $table->unique('email');    加入唯一索引。
    $table->unique('state', 'my_index_name');   自定義索引名稱。
    $table->index('state'); 加入基本索引。

98.數據填充命令

php artisan make:seeder UsersTableSeeder

99.運行數據填充

php artisan db:seed --class=UserTableSeeder

100.Eloquent中數據表關聯

class Flight extends Model
{

    protected $table = 'my_flights';
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,673評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,668評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,004評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,173評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,705評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,426評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,656評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,833評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,371評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,621評論 2 380

推薦閱讀更多精彩內容