laravel blog 二

  1. 修改数据库articles结构,添加到user表的外键,migrate:refresh
        public function up()
        {
            Schema::create('articles', function (Blueprint $table) {
                $table->increments('id');
                $table->integer('user_id')->unsigned();
                $table->string('title');
                $table->text('body');
                $table->timestamp('publishedAt');
                $table->timestamps();
                $table->foreign('user_id')
                      ->references('id')
                      ->on('users')
                      ->onDelete('cascade');
            });
        }
  2. model添加关系函数,一对多的关系,函数名可以自己定义。
    //user
        public function articles(){
            return $this->hasMany('Apparticle');
        }
    
    //article
        protected $fillable = [
            'title',
            'body',
            'publishedAt',
            'user_id'   //临时添加字段
        ];
    
        public function user()
        {
            return $this->belongsTo('Appuser');
        }
  3. 这个时候就可以在tinker里面添加数据,进行测试了。
  4. 提取view的edit,create的表单form,在form里临时添加字段
    {!! Form::hidden('user_id', 1) !!}
  5. route添加验证路由
    Route::controllers([
        'auth'=>'AuthAuthController',
        'password'=>'AuthPasswordController'
        ]);
  6. auth/login测试验证成功后,删除临时字段,修改AritcleController
        public function store(ArticleRequest $request)
        {
            $article = new Article($request->all());
            Auth::user()->articles()->save($article);
            //Article::create($input);
    
            return  redirect('articles');
    
        }
  7. Middware,在Kernel.php里面,此文件就在Routes.php旁边。在AritcleController引用已经存在的auth
    class ArticleController extends Controller
    {
    
        public function __construct()
        {
            $this->middleware('auth', ['except'=>'index']);
        }
    ..........
    }

    这样就搞定了,再次访问总会跳转到登陆界面,除了index

  8. 想要自己建立一个middleware,php artisan make:middleware demo ,在handle函数分配跳转,在模型里面写判断函数,在Kernel.php进行注册,运行。
原文地址:https://www.cnblogs.com/fenle/p/4805941.html