Laravel基礎知識

tomlibao發表於2021-06-09

1、安裝composer

2、執行命令:

composer create-project laravel/laravel 專案資料夾名 --prefer-dist

在這裡插入圖片描述

  • app:應用程式的核心程式碼

  • bootstrap:一個引導框架的app.php檔案,一個cache目錄(包含路由及快取檔案),框架啟動檔案,一般情況不動。

  • config:所有配置檔案

  • database:其中migrations目錄可以生成資料表。

  • public:入口檔案存放地,以及靜態資源(和tp類似)

  • resources

  • routes:應用的所有路由定義

  • tests:可用來單元測試

  • vendor:所有composer依賴包

1、常見的幾種請求

  • Route::get($url,$callback);
  • Route::post($url,$callback);
  • Route::put($url,$callback);
  • Route::delete($url,$callback);

2、匹配指定的請求方式

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

});

3、配置任意請求方式

Route::any('/home', function () {

});

4、給路由加必填引數

Route::get('/home/{id}', function ($id) {
    echo 'id為:'.$id;
});

5、給路由增加可選引數

Route::get('/home/{id?}', function ($id = '') {
    echo 'id為:'.$id;
});

6、通過?形式傳遞get引數

Route::get('/home', function () {
    echo 'id為:'.$_GET['id'];
});

7、給路由增加別名

Route::any('/home/index', function () {
    echo '測試';
})->name('hh');

8、設定路由群組

例如有如下路由:

  • /admin/login
  • /admin/index
  • /admin/logout
  • /admin/add

如果一個一個新增是比較麻煩的,他們有一個共同的區別,都是有/admin/字首,可設定一個路由群組進行新增:

Route::group(['prefix'=>'admin'], function () {
    Route::get('test1', function () {
        echo 'test1';
    });
    Route::get('test2', function () {
        echo 'test2';
    });
});

此時就可通過/admin/test1來進行訪問了。

9、路由配置控制器

控制器可以建一個前臺和一個後臺:

在這裡插入圖片描述

命令列建立路由:

php artisan make:controller Admin/IndexController

基本路由建立:

Route::get('test/index','TestController@index');

分目錄路由建立:

Route::get('/admin/index/index','Admin\IndexController@index');

引入:use Illuminate\Support\Facades\Validator

$param = $request->all();
$rule = [
    'name'=>'required|max:2',
];
$message = [
    'required'  => ':attribute不能為空',
    'max' => ':attribute長度最大為2'
];
$replace = [
    'name' => '姓名',
];
$validator = Validator::make($param, $rule, $message,$replace);
if ($validator->fails())
{
    return response()->json(['status'=>0,'msg'=>$validator->errors()->first()]);
}

在控制器中如果要使用一個類,例如use Illuminate\Http\Request,就可以簡寫為use Request
但是需要在config目錄下的app.php配置檔案中加入:

'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Arr' => Illuminate\Support\Arr::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
        'Blade' => Illuminate\Support\Facades\Blade::class,

        'Request' => Illuminate\Support\Facades\Request::class,

    ],

1、獲取使用者單個輸入值:

Input::get('id')

2、獲取使用者輸入的所有值:

Input::all()

列印出來的是陣列

關於dd(dump+die)

3、獲取使用者輸入指定的值:

Input::only(['id','name']  //只接收id,其餘不接受

4、獲取使用者輸入指定值之外的值:

Input::except(['name']    //不接收name,其餘都接收

5、判斷某個值是否存在

Input::has('name')    //存在返回true  不存在返回false  其中0返回true

1、檢視的建立

檢視也可分目錄管理:

在這裡插入圖片描述
控制器語法:

return view('home/test');

也可寫為:

return view('home.test');

2、變數對映

控制器中:

return view('home/test',['day'=>time()]);

檢視中:

{{$day}}

其中控制器中變數對映有三種:

  • view(模板檔案,陣列)
  • view(模板檔案)->with(陣列)
  • view(模板檔案)->with(陣列)->with(陣列)

瞭解一下compact陣列。

3、檢視渲染

3.1 foreach的使用

控制器中:

public function index(){

        $arr = [
            0 => [
                'name' => 'tom',
                'age' => '12',
            ],
            1 => [
                'name' => 'bby',
                'age' => '13',
            ]
        ];
        return view('home/test',['data'=>$arr]);
    }

檢視中:

@foreach($data as $k=>$v)
    鍵:{{$k}}
    值:{{$v['name']}}
    <br/>
@endforeach

3.2 if的使用

@if(1==2)
    是的
@else
    不是的
@endif

4、檢視之間的引用

@include('welcome')

1、建立模型的命令

php artisan make:model Model/Admin/Member

此時,就會在app目錄內建立:
在這裡插入圖片描述

2、模型基本設定

<?php

namespace App\Model\Admin;

use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    //定義表名
    protected $table = 'student';
    //定義主鍵
    protected $primaryKey = 'id';
    //定義禁止操作時間
    public $timestamps = false;
    //設定允許寫入的欄位
    protected $fillable = ['id','sname'];

}

3、模型資料新增

方式一:

     $model = new Member();
     $model->sname = '勒布朗';
     $res = $model->save();
     dd($res);

方式二:

     $model = new Member();
     $res = $model->create($request->all());
     dd($res);

4、模型的表連線

//查詢客戶與銷售顧問的客資列表
$data = Custinfo::select(['custinfo.*', 'customers.name'])
    ->join('customers', 'customers.id', '=', 'custinfo.cust_id')
    ->where($where)
    ->get()
    ->toArray();

5、簡單模型關聯一對一

<?php


namespace App\Model\Admin;


use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    //定義表名
    protected $table = 'phone';

    //定義主鍵
    protected $primaryKey = 'id';

    //定義禁止操作時間
    public $timestamps = false;

    //設定允許寫入的欄位
    protected $fillable = ['id','uid','phone'];
}
<?php

namespace App\Model\Admin;

use Illuminate\Database\Eloquent\Model;

class Member extends Model
{
    //定義表名
    protected $table = 'student';

    //定義主鍵
    protected $primaryKey = 'id';

    //定義禁止操作時間
    public $timestamps = false;

    //設定允許寫入的欄位
    protected $fillable = ['id','sname'];

    /**
     * 獲取與使用者關聯的電話號碼記錄。
     */
    public function getPhone()
    {
        return $this->hasOne('App\Model\Admin\Phone', 'uid', 'id');
    }

}
    //物件轉陣列
    public function Arr($obj)
    {
        return json_decode(json_encode($obj), true);
    }


    public function index(){
        $infoObj = Member::with('getPhone')->get();
        $infoArr = $this->Arr($infoObj);
        print_r($infoArr);
    }

在這裡插入圖片描述
在這裡插入圖片描述

1、自定義日誌目錄

config目錄下的logging.php中的channels配置:

 'custom' => [
     'driver' => 'single',
     'path' => storage_path('logs/1laravel.log'),
     'level' => 'debug',
 ]

控制器中:

$message = ['joytom','rocker'];
Log::channel('custom')->info($message);

建立一個遷移檔案:php artisan make:migration create_shcool_table

會在database\migrations下建立一個檔案:
在這裡插入圖片描述
在up方法中增加如下程式碼:

<?php

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

class CreateShcoolTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('shcool', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('school_name','20')->notNull()->unique();

            $table->tinyInteger('status')->default(1);

            $table->timestamps();
        });
    }

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

更詳細的生成SQL方法請參考:資料遷移檔案常用方法速查表

寫好SQL檔案以後,執行:php artisan migrate
在這裡插入圖片描述
將會生成資料表,其中操作日誌將記錄在這個表中:

在這裡插入圖片描述
php artisan migrate:rollback:回滾最後一次的遷移操作, 刪除(回滾)之後會刪除遷移記錄,並且資料表也會刪除,但是遷移檔案依舊存在,方便後期繼續遷移(建立資料表)。

1、將DB查出後的物件轉為陣列

$info = DB::table('sd_note')->get()->map(function ($value){
            return (array)$value;
        })->toArray();
本作品採用《CC 協議》,轉載必須註明作者和本文連結