分类目录归档:Laravel

Laravel视图composer传递数据到视图

  • 全局共享变量

    public function boot()
    {
        view()->share('tasks',Task::all());
    }
    

使用view()->share(),最好放在服务提供者的boot()方法中如:App\Providers\AppServiceProvider

  • 基于闭包的视图composer
        view()->composer('home',function($view){
            $view->with('tasks',Task::all());
        });

以上代码使用闭包的方式,将变量传递给指定的单个视图home表示resources/views/home.blade.php,如果要传给多个视图,可以使用[文件夹路径.*],或者将composer方法的第一个参数与成数组[‘xx.header’,’xx.footer’]

  • 基于类的视图composer

    <?php namespace App\Http\ViewComposers;
    
    use App\Task; use Illuminate\Contracts\View\View;
    
    class TasksComposer { private $tasks;
    
        public function __construct(Task $tasks)
        {
            $this->tasks = $tasks;
        }
    
        public function compose(View $view){
            $view->with('tasks',$this->tasks->all());
        }
    
    
    }
    

创建视图composer类TasksComposer,在boot()方法中使用view()->composer(‘home’,TasksComposer::class);代码,给对应的视图传递变量;

0

Vagrant/Homestead常用命令

$ vagrant init # 初始化

$ vagrant up # 启动虚拟机
$ vagrant halt # 关闭虚拟机
$ vagrant reload # 重启虚拟机
$ vagrant ssh # SSH 至虚拟机
$ vagrant suspend # 挂起虚拟机
$ vagrant resume # 唤醒虚拟机
$ vagrant status # 查看虚拟机运行状态
$ vagrant destroy # 销毁当前虚拟机

box管理命令

$ vagrant box list # 查看本地box列表
$ vagrant box add # 添加box到列表
$ vagrant box remove # 从box列表移除

0

laravel表单验证中使用中文提示

/**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|min:3',
            'content' => 'required',
            'published_at' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'required' => ':attribute是必需的',
            'min' => ':attribute最少:min位',
        ];
    }
0

phpunit基础写法

<?php
/**
 * Created by PhpStorm.
 * User: Connie
 * Date: 2019/3/30
 * Time: 16:20
 */

namespace Tests\Unit;


use App\Order;
use App\Product;
use Tests\TestCase;

class OrderTest extends TestCase
{
    /** @var Order $order */
    protected $order;
    protected $iWatch;
    protected $macBook;

    public function setUp()
    {
        $this->order = new Order();
        $this->iWatch = new Product();
        $this->iWatch->setName('i watch');
        $this->iWatch->setPrice(5000);
        $this->macBook = new Product();
        $this->macBook->setName('macBook Pro');
        $this->macBook->setPrice(12000);

        $this->order->add($this->iWatch);
        $this->order->add($this->macBook);
    }

    /** @test */
    public function order_can_consists_products()
    {
        $this->assertEquals(2, count($this->order->getProducts()));
    }

    /** @test */
    public function we_can_get_price_from_an_order()
    {
        $this->assertEquals(17000,$this->order->total());
    }

}

0