歸納整理Laravel基礎知識總結

本篇文章給大家帶來了關于laravel的相關知識,其中主要介紹了一些基礎知識,包括了怎么安裝laravel、路由、驗證器、視圖等等相關內容,下面一起來看一下,希望對大家有幫助。

歸納整理Laravel基礎知識總結

【相關推薦:laravel

一、安裝laravle

1、安裝composer

2、執行命令:

composer create-project laravel/laravel 項目文件夾名 –prefer-dist

歸納整理Laravel基礎知識總結

二、目錄簡介

  • app:應用程序的核心代碼

  • bootstrap:一個引導框架的app.php文件,一個cache目錄(包含路由及緩存文件),框架啟動文件,一般情況不動。

  • config:所有配置文件

  • database:其中migrations目錄可以生成數據表。

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

  • resources:

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

  • tests:可用來單元測試

  • vendor:所有composer依賴包

三、路由初識

1、常見的幾種請求

  • Route::get( ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? u ? ? ? ? ? ? ? ? ? ? ? ? r ? ? ? ? ? ? ? ? ? ? ? ? l ? ? ? ? ? ? ? ? ? ? ? ? , ? ? ? ? ? ? ? ? ? ? ? ? ? ?url, ? ? ? ? ? ? ? ? url,callback);
  • Route::post( ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? u ? ? ? ? ? ? ? ? ? ? ? ? r ? ? ? ? ? ? ? ? ? ? ? ? l ? ? ? ? ? ? ? ? ? ? ? ? , ? ? ? ? ? ? ? ? ? ? ? ? ? ?url, ? ? ? ? ? ? ? ? url,callback);
  • Route::put( ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? u ? ? ? ? ? ? ? ? ? ? ? ? r ? ? ? ? ? ? ? ? ? ? ? ? l ? ? ? ? ? ? ? ? ? ? ? ? , ? ? ? ? ? ? ? ? ? ? ? ? ? ?url, ? ? ? ? ? ? ? ? url,callback);
  • Route::delete( ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? u ? ? ? ? ? ? ? ? ? ? ? ? r ? ? ? ? ? ? ? ? ? ? ? ? l ? ? ? ? ? ? ? ? ? ? ? ? , ? ? ? ? ? ? ? ? ? ? ? ? ? ?url, ? ? ? ? ? ? ? ? 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、路由配置控制器

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

歸納整理Laravel基礎知識總結

命令行創建路由:

php artisan make:controller Admin/IndexController

基本路由建立:

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

分目錄路由建立:

Route::get('/admin/index/index','AdminIndexController@index');

四、laravel驗證器

引入:use IlluminateSupportFacadesValidator

$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 IlluminateHttpRequest,就可以簡寫為use Request。
但是需要在config目錄下的app.php配置文件中加入:

'aliases' => [          'App' => IlluminateSupportFacadesApp::class,         'Arr' => IlluminateSupportArr::class,         'Artisan' => IlluminateSupportFacadesArtisan::class,         'Auth' => IlluminateSupportFacadesAuth::class,         'Blade' => IlluminateSupportFacadesBlade::class,          'Request' => IlluminateSupportFacadesRequest::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、視圖的創建

視圖也可分目錄管理:

歸納整理Laravel基礎知識總結
控制器語法:

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目錄內創建:
歸納整理Laravel基礎知識總結

2、模型基本設置

<?phpnamespace AppModelAdmin;use IlluminateDatabaseEloquentModel;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、簡單模型關聯一對一

<?phpnamespace AppModelAdmin;use IlluminateDatabaseEloquentModel;class Phone extends Model{     //定義表名     protected $table = 'phone';      //定義主鍵     protected $primaryKey = 'id';      //定義禁止操作時間     public $timestamps = false;      //設置允許寫入的字段     protected $fillable = ['id','uid','phone'];}
<?phpnamespace AppModelAdmin;use IlluminateDatabaseEloquentModel;class Member extends Model{     //定義表名     protected $table = 'student';      //定義主鍵     protected $primaryKey = 'id';      //定義禁止操作時間     public $timestamps = false;      //設置允許寫入的字段     protected $fillable = ['id','sname'];      /**      * 獲取與用戶關聯的電話號碼記錄。      */     public function getPhone()     {         return $this->hasOne('AppModelAdminPhone', '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);     }

歸納整理Laravel基礎知識總結
歸納整理Laravel基礎知識總結

八、日志

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

會在databasemigrations下創建一個文件:
歸納整理Laravel基礎知識總結
在up方法中增加如下代碼:

<?phpuse IlluminateDatabaseMigrationsMigration;use IlluminateDatabaseSchemaBlueprint;use IlluminateSupportFacadesSchema;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
歸納整理Laravel基礎知識總結
將會生成數據表,其中操作日志將記錄在這個表中:

歸納整理Laravel基礎知識總結
php artisan migrate:rollback:回滾最后一次的遷移操作, 刪除(回滾)之后會刪除遷移記錄,并且數據表也會刪除,但是遷移文件依舊存在,方便后期繼續遷移(創建數據表)。

【相關推薦:laravel

? 版權聲明
THE END
喜歡就支持一下吧
點贊8 分享