关于laravel基础知识

时间:2023-03-09 00:23:23
关于laravel基础知识

laravel任务管理知识点

1.配置数据库环境

首先要找到congif/app.php,在这里会发现一些全局的系统设置,包括语言,时区等。

重要的是会发现前几个数组都使用了env()这个函数,这个时候找到根目录下的.env文件 会发现一些全局配置和数据库连接配置

找到第二个模块

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Homestead
DB_USERNAME=Homestead
DB_PASSWORD=secret

在这里进行数据库配置

2.php artisan make:auth

创建系统自带的View Controller 并且自动更新了路由

D:\wamp\www\laravel\resources/views/auth/login.blade.php
D:\wamp\www\laravel\resources/views/auth/register.blade.php
D:\wamp\www\laravel\resources/views/auth/passwords/email.blade.php
D:\wamp\www\laravel\resources/views/auth/passwords/reset.blade.php
D:\wamp\www\laravel\resources/views/auth/emails/password.blade.php
D:\wamp\www\laravel\resources/views/layouts/app.blade.php
D:\wamp\www\laravel\resources/views/home.blade.php
D:\wamp\www\laravel\resources/views/welcome.blade.php

Installed HomeController
Updated Routes File

视图在\resources\views\ 并且创建了一个larouts文件夹和一个app.blade.php的视图模板

控制器\app\Http\Controllers   \app\Http\Controllers

路由更新了

Route::auth();

Route::get('/home', 'HomeController@index');

再次刷新localhost主页,会显示出一个做好站点

但是make:auth最好在项目开始的时候使用,以后覆盖已经创建好的文件

3.

php artisan make:model Project -m

创建一个Project模型,并使用迁移文件

D:\wamp\www\laravel>php artisan make:model Project -m
 Model created successfully.
mCreated Migration:2016_11_01_213249_create_projects_table

创建好以后,在app目录下面会发现一个  Project.php

在database\migrations下会多出一个迁移文件2016_11_01_213249_create_projects_table.php

4.一对多模型  以 User 和 Project为例

一个User 可以有多个Project ,而一个Project必定属于某一个User

在app\User.php User类 中定义一个公共函数

public function projects()
{
    return $this->hasMany('App\Project');
}

表示执行这个函数的时候,App\Project这个模型就和User这个模型产生了关系

一个User拥有多个 Project,可以找到这些个projects

在app\Project.php  Project类中定义一个公共函数

public function user()
{
    $this->belongsTo('App\User');
}

表示执行这个函数的时候,App\User这个模型就和Project这个模型产生了关系

一个Project 属于一个User,可以找到这个user

这个时候,再写一个公共函数

public function tasks()
{
    return $this->hasMany('App\Task');
}

意义同上,这样 Project和Task又搞上关系了

那么User和Task也可以搞上关系了,在User类中定义一个公共函数

User has many Task through Project

public function tasks()
{
   return $this->hasManyThrough('App\Task','App\Project');
}

5.php artisan migrate

这个命令是根据在\database\migrations 下面的数据迁移文件,在数据库创建相应的数据表

比如在\database\migrations下有四个文件

执行命令以后

Migration table created successfully.
2014_10_12_100000_create_password_resets_table
2016_11_01_213249_create_projects_table
2016_11_01_213629_create_tasks_table

然后在数据表中,会有4个同名文件和一个migration表(用于记录数据表的操作,进行版本控制)

是利用迁移文件up()函数中引用 Blueprint这个类来生成的

以2014_10_12_000000_create_users_table为例

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->rememberToken();//用于记录在线状态

//对应update_at和create_at时间戳
        $table->timestamps();

});
}

$table调用的每一个方法都对应表中的某一个字段属性,前者为字段类型,参数为字段名称

比如:Blueprint.php中

public function increments($column)
{
    return $this->unsignedInteger($column, true);
}

可以根据自己的需要添加字段,比如在project的迁移文件中

public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->increments('id');//自增主键id
        $table->string('name');//字符串 name
        $table->string('thumbnail');//字符串 thumbnail

//整型user_id 用于关联project与user之间的关系

//user可以根据user_id找到相应的project
        $table->integer('user_id');
        $table->timestamps();
    });
}

更改好迁移文件后,需要将数据库更新一下

执行php artisan migrate:rollback 数据库回滚操作

D:\wamp\www\laravel>php artisan migrate:rollback
2016_11_01_213629_create_tasks_table
2016_11_01_213249_create_projects_table
2014_10_12_100000_create_password_resets_table
2014_10_12_000000_create_users_table

执行php artisan migrate 根据蓝图创建数据表

D:\wamp\www\laravel>php artisan migrate
2014_10_12_000000_create_users_table
2014_10_12_100000_create_password_resets_table
2016_11_01_213249_create_projects_table
2016_11_01_213629_create_tasks_table

或者直接执行  php artisan migrate:refresh  对数据库根据蓝图进行更新

6.在\app\Http 下的 routes.php 这里是定义整个项目路由的地方

比如

Route::get('/', function () {
    return view('welcome');
});

当登陆主页的时候,没有路由参数就通过匿名函数返回一个叫welcome的试图

视图定义在:\resources\views 下,默认的CSS框架是bootstrap框架

7.对于一个模板文件,不应该放太多杂乱的内容,可以将功能分开,比如引用一个模态框,就可以在\resources\views 创建projects文件下,并创建_createProjectModel.blade.php文件(视图格式:试图名.blade.php),专门用于存放创建模态框的代码,在模板视图文件中,只要@include(‘projects/_createProjects’);便可以引入. @include指向以\resources\views为起始地址

8.视图模板js、css的文件引入可以用{{asset()}}

比如

<link rel="stylesheet" href="{{asset('css/bootstrap.min.js')}}" >

asset()默认指向public文件下

9.使用composer update可以加载在根目录下 composer.json required里添加的文件,加载的文件在vendor目录下,并且在config\app.php下找到 provides 这个数组 按照路径加载进去,默认以vendor为起点。比如Collective\Html\HtmlServiceProvider::class并且在下面的 aliases中使用别名

10.关于 {{ }}  和{!! !!}

{{ }}语句已经通过 PHP 的 htmlentities 函数处理以避免 xss 攻击

{!! !!}采用原样输出

11.模板提示问题

D:\wamp\www\laravel\storage\framework\views\645c1fe367a6e0cbe4028d9bfe4798189f279b72.php line 29:

可能一下子不知道是那个html文件写错了,所以就根据它只想的目录,找到相应的缓存文件,查出错误,并且找到对应的模板,更改错误

12.路由 在app\http\ routes.php来配置全局路由

基本形式为:

Route::fangshi(‘/routename’,’XXXController@action’)

fangshi:请求方式  routename:请求名   XXXController控制器名  action 方法名

或者

Route::fangshi(‘/routename’,function(){

//通过回调函数执行操作

});

或者!

Route::resource(‘projects’,’ProjectsController’);

这个就是一下子拥有了ProjectsController的CRUD所有方法,但是要执行composer命令

php artisan make:controller ProjectsController --resource

在ProjectsController创建了一系列的方法,对应的路由和提交方式如下:

如果没有--resource 则只会创建一个不包含方法的ProjectsController

13.关于前端页面跳转页面的指定

可以用{{url(‘route1/route2’)}} url默认指向根目录路由

推荐{{route(‘routename’)}} 通过路由命名指向,以免后期更改路由

14.关于中间件

中间件是在路由上面加了一层保护层,如果使用了中间件,对于路由请求,都会先进行中间件的过滤,不满足条件的,进行处理,满足条件的才会根据路由做出相应的响应。

比如auth这个中间件,在kernel.php中是这样定义的,

'auth' => \App\Http\Middleware\Authenticate::class,

再去查看Authenticate这个类

<?php

namespace App\Http\Middleware;

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

class Authenticate
{
    /**
     * 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)->guest()) {
            if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        return $next($request);
    }
}

大致浏览代码,知道这个类的功能是:对于请求,如果这个请求是游客(未登录用户),返回 401或者直接打回login页面,如果有登陆过后,不进行处理。

也就是说auth这个中间件的对未登陆游客的路由请求进行屏蔽,打回登陆界面或者401;

自定义中间件,你也可以使用自定义中间件

1.php artisan make:middleware Mymiddleware

执行这条命令以后会在app\http\middleware下生成一个Mymiddleware.php

2.然后在app\http\Kernel.php中,找到 protected $routeMiddleware将新注册的中间件加入其中。

3.注册完中间件以后,就可以在路由中使用,或者在控制器中使用

15.相对于user关联了projects,在某一个user建立自己的projects的时候,可以从user projects他们之间的关联关系入手

$request->user()->projects()->create([
    'name'=>$request->name,
    'thumbnail'=>null
]);

这样,每个user就只能创建自己的projects

使用create()方法的时候,laravel会有一种保护机制,就是只有表单中指定的字段$fillable可以上传或者指定的字段不能上传 $guard

Project.php

protected $fillable =[
  'name','thumbnail'
];

16.关于代码重构

代码重构是一个项目的重要组成,一个好的代码重构是非常简洁舒服的,把相同的功能封装成一个类方法,其他需要用的地方直接引用这个类方法,达到重用的效果。

对于引入类的注入,可以使用方法注入或者构造函数注入。

例子:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Repositories\Projects;

class ProjectsController extends Controller
{
    protected $repo;
    public function __construct(Projects $repo)
    {
        $this->repo = $repo;
    }

    public function store(Request $request)
    {
    $this->repo->newProject($request);
    return '创建成功';

    }

}

Projects.php

<?php
namespace App\Repositories;

use Intervention\Image\Facades\Image;
class Projects {
    public function newProject($request)
    {
        $request->user()->projects()->create([
            'name'=>$request->name,
            'thumbnail'=>$this->thumbnail($request),
        ]);
    }
    public function thumbnail($request)
    {
        if ($request->hasFile('thumbnail')){
            $file = $request->thumbnail;
            $name = str_random(10).'.jpg';
            $path = public_path().'/thumbnails/'.$name;
            Image::make($file)->resize(261,98)->save($path);
            return $name;
        }
    }
}

先引入所需要的重构类use App\Repositories\Projects;

将其注入到构造函数中,并命名为 $repo

protected $repo;
public function __construct(Projects $repo)
{

//将$repo这个类赋予本类的属性 $repo
    $this->repo = $repo;
}

//$this->repo指向App\Repositories\Projects这个类

//相当于//App\Repositories\Projects::newProject($request);

$this->repo->newProject($request);
return '创建成功';

17.php artisan make:request CreateProjectRequest

创建一个请求验证方法,在\app\Http\Requests目录下

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateProjectRequest extends Request
{
    /**
     * 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 [
            'name'=>'required|unique:projects',
            'thumbnail'=>'image|dimensions:min_width=261,min_height=98',

        ];
    }

    public function messages()
    {
        return [
          'name.required'=>'项目名称必须填写',
          'name.unique'=>'项目名称已经存在',
          'thumbnail.image'=>'请上传图片格式的文件',
          'thumbnail.dimensions'=>'请上传图片最小为261X98PX的图片',
        ];
    }
}

这里的 rules方法为表单的验证条件,数组键name,thumbnail分别对应form表单中的name和thumbnail,值是验证的条件

messages()是当条件不通过的时候,每一个错误条件对应的错误信息,如果没有定义这个方法,那么就按照默认的英文提示信息

写好这个类以后,要将这个类放入需求的地方,先引入命名空间,然后原本地方方法中注入的Request替换为 CreateProjectRequest,CreateProjectRequest是Request子类。

在laravel中,有一个全局变量$errors用于获取错误 $errors->any()表示有任何错误,$errors->all()取出所有错误,在blade模板中,可以这样输出错误信息

@if($errors->any())

    <ul  class="alert alert-danger">
        @foreach($errors->all() as $error)
            <li>{{$error}}</li>
        @endforeach
    </ul>

@endif