laravel记录

1.使用数据库事务的时候需要传递参数,使用了use关键字,否则的话传递不进去,代码如下:

    public function postVote(Request $request){
        $data = $request->all();
        $count = DB::table("vote")->where("workdid",$data['id'])->where("ip", $data['ip'])->count();


        if(DB::table("vote")->where("workdid",$data['id'])->where("ip", $data['ip'])->count()>0){
            $ret = ['state' => 'fail', 'message' => '您已经给这个作品投过一票!'];
        }else{
            DB::transaction(function () use($data){
                DB::table("work")->where("id", $data["id"])->increment("vote");
                DB::table("vote")->insert(["workdid"=>$data["id"], "ip"=>$data['ip']]);
            });
            $ret = ['state' => 'success', 'message' => '投票成功'];
        }
        return response()->json($ret);
    }

 

2.分页的时候需要把参数带进去,使用appends()方法,还要显示总共多少条记录,代码如下,前提是$list是查询构建起调用paginate()方法返回的结果

        <div class="summary">
            共有 {{$list->total()}} 条数据
        </div>
        @if ($list->hasPages())
            <div class="pager">
                {!! $list->appends($appends)->render() !!}
            </div>
        @endif

 

3.向主页面中追加内容的时候,主页面内容如下

@section('sidebar')
    This is the master sidebar.
@show

子页面内容如下:

@section('sidebar')
    @parent
    <p>This is appended to the master sidebar.</p>
@endsection

注意主页面@section的结束语句是@show,不是@endsection,同时子页面中使用@parent表明是追加的内容

 

4.很多javascript框架使用{{}}来表示要输入到浏览器中的表达式,可以使用@告诉blade引擎该表达式保持原生格式不做改动例如:

<h1>Laravel</h1>
Hello, @{{ name }}.

就是说如果要使用javascript框架中使用到{{}},那么前面要加@

 

5.Laravel5路由\home 无法访问
在apache配置文件中将所有的 AllowOverride none;设置为AllowOverride all;配置文件具体位置因系统不同而改变,ubuntu14.0.1LTS 版本在/etc/apache2/apache2.conf文件中

 

6.部署好之后500错误

安装完laravel后,打开马上出现了500错误,配置都是正确的,但是出现了500错误
------------------>`500 (Internal Server Error)`
要给缓存文件设置777权限,如下
chmod -R 777 storage (给storage 777权限)

 

7.仅能有一个AI
有一次使用php artisan migrate ------->结果报错了
原因是主键id是AI,而设置一个外键xx_xx_id是integer类型,这就冲突了,解决方法只需将xx_xx_id改为unsigned integer类型
(像这样的$table->integer('role_id')->unsigned();)

 

8.邮件发送530错误
邮箱发送出现了如下问题:Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required,
从错误吗中看出是配置错误,但是我们检查了几次都是正确的,原因是缓存问题,这时候可以
清除缓存php artisan cache:clear或重启服务器php artisan serv

 

9.使用create插入数据错误

如果使用create出现MassAssignmentException in Model.php line 448

从错误中看出是模型中没有定义白名单字段,解决如下:

class Contacts extends Model
{
  protected $fillable = ['name', 'mobile', 'email', 'address', 'created_at', 'updated_at'];
}

 

10.compose update报错
错误为:Fatal error: Uncaught exception 'ReflectionException' with message 

解决方法可能如下:
1. composer dump-autoload
2. 配置文件错误,需修改,如我安装时改了配置文件.env,然后报错,这时候还原.env 就正常了


11.默认情况下刀片语法的{{}}已经通过php的htmlentitys函数处理避免XSS攻击,如果不想数据被处理,显示原生的数据可以用下面的方法

Hello, {!! $name !!}.

 

12.运行命令php artisan migrate莫名其妙的错误

        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug')->unique();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
            $table->timestamps('updated_at')->index();
        });

这样会报错: 

[Symfony\Component\Debug\Exception\FatalThrowableError]
Fatal error: Call to a member function index() on null

改成下面就好了

        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug')->unique();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
            $table->timestamps('published_at')->index();
        });

 

 13.修改phpstorme中的编码格式
FILE->Setting->Editor->File Encoding->将UTF-8改成GBK 

 

14.laravel命令集合
1)查看应用中所有的路由:php artisan route:list
2)创建控制器: php artisan make:controller BlogController --plain    --plain参数表示命令用于创建一个空的控制器而不是标准的 RESTful 风格控制器
3)创建model: php artisan make:model --migration Post   创建Post模型并创建迁移文件
4)创建中间件:php artisan make:middleware OldMiddleware 创建一个OldMiddleware的中间件

 

15.定义一个token,妈蛋记不住

{'_token': '{{ csrf_token() }}', 'dir': 'product'}
{{ csrf_field() }}
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

 

 16.使用captcha验证码第三方插件的时候验证随机数是否正确,写法如下

        $data = $request->all();
        $attributes = [
            'name'=>'用户名',
            'password'=>'密码',
            'captcha' =>'验证码'
        ];
        $validator = \Validator::make(
            $data,
            [
                'name' => 'required',
                'password' => 'required',
                'captcha' => 'required|captcha',
            ],
            [
                'required' => ":attribute不能为空",
                'captcha.required' => '请输入验证码',
                'captcha.captcha' => '验证码错误,请重试'
            ],
            $attributes
        );

 

17.发送手机验证码的时候使用validator验证手机验证码是否正确

发送验证码代码如下

    public function postValidatecode(Request $request){
        $data = $request->all();
        $code = rand(1000, 9999);
        session([config('session.session_key.register')=>$code]);
        $content = "您好,您本次注册的验证码是" . $code . ',请妥善保管。';
        $result = sendsms($data['mobile'], $content);
        return \Response::json($result);
    }

验证这个验证码是否正确如下

        $data = $request->all();
        $attributes = [
            'name'=>'用户名',
            'password'=>'密码',
            'password_confirmation'=>'确认密码',
            'mobile'=>'手机号',
            'idNo'=>'身份证号',
            'validateCode'=>'验证码',
        ];
        $rules = [
            'name'=>'required|unique:users',
            'password' => array('bail', 'required', 'confirmed', 'regex:/^\w{6,15}$/'),
            'password_confirmation' => 'required',
            'mobile' => array('required','regex:/^1[3|4|5|6|7|8|9]\d{9}$/', 'unique:users'),
            'validateCode'=>array('required', 'validatesmsg:register'),
            'idNo'=> array('required','regex:/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/i'),
            'agree' => 'required',
        ];

app\Providers\AppServiceProvider.php中的扩展方法如下,原理很简单就是验证这个session是否相等

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Validator::extend('validatesmsg', function($attribute, $value, $parameters){
            return $value == session(config('session.session_key.'.$parameters[0]));
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

 

posted @ 2016-08-03 13:00  nd  阅读(591)  评论(0编辑  收藏  举报