laravel5.3 vue 實現收藏夾功能

laravel5.3 vue 實現收藏夾功能

本篇是接着 laravel中使用WangEditor及多圖上傳(下篇)
因此咱們這裏不演示怎麼新建項目了。

1. laravel項目安裝


下載以前的項目,完成安裝。
php

1.0 寫在以前的(before)

爲了不後面踩到vue版本的坑,請務必閱讀此部分

1.0.1 修改package.json

{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-14",
    "laravel-elixir-vue-2": "^0.2.0",
    "laravel-elixir-webpack-official": "^1.0.2",
    "lodash": "^4.16.2",
    "vue": "^2.0.1",
    "vue-resource": "^1.0.3"
  }
}

1.0.2 修改gulpfile.js

將原來的require('laravel-elixir-vue');
修改成require('laravel-elixir-vue-2');
css

const elixir = require('laravel-elixir');
​
require('laravel-elixir-vue-2');
​
/*
 |--------------------------------------------------------------------------
 | Elixir Asset Management
 |--------------------------------------------------------------------------
 |
 | Elixir provides a clean, fluent API for defining some basic Gulp tasks
 | for your Laravel application. By default, we are compiling the Sass
 | file for our application, as well as publishing vendor resources.
 |
 */
​
elixir(mix => {
    mix.sass('app.scss')
       .webpack('app.js');
});


1.0.3 修改resource/assets/js/app.js

將原來的el: 'body'改成el: '#app'
vue

const app = new Vue({
    el: '#app'
});

1.1 安裝npm 模塊

(若是以前沒有執行此操做)
jquery

npm  install


1

1.2 建立模型及遷移

咱們須要一個User模型(laravel附帶),一個Post模型和一個Favorite模型以及它們各自的遷移文件。
由於咱們以前建立過了Post的模型,因此咱們只須要建立一個Favorite模型便可。
webpack

php artisan make:model App\Models\Favorite -m


2

這會建立一個Favorite模型以及遷移文件。
ios

1.3 修改posts遷移表及favoritesup方法

posts表在id字段後面新增一個user_id字段
laravel

php artisan make:migration add_userId_to_posts_table --table=posts

修改database/migrations/2018_01_18_145843_add_userId_to_posts_table.phpgit

public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->integer('user_id')->unsigned()->after('id');
        });
    }


database/migrations/2018_01_18_142146_create_favorites_table.php
github

public function up()
    {
        Schema::create('favorites', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('post_id')->unsigned();
            $table->timestamps();
        });
    }


favorites表包含兩列:
web

user_id 被收藏文章的用戶ID。
post_id 被收藏的帖子的ID。


而後進行表遷移

php artisan migrate

1.4 用戶認證

由於咱們以前就已經建立過了,因此這裏就不須要重複建立了。

若是你沒有建立過用戶認證模塊,則須要執行 php artisan make:auth

2. 完成蒐藏夾功能

修改routes/web.php

2.1 建立路由器

​
Auth::routes();
​
Route::post('favorite/{post}', 'ArticleController@favoritePost');
Route::post('unfavorite/{post}', 'ArticleController@unFavoritePost');
​
Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');

2.2 文章和用戶之間多對多關係

因爲用戶能夠將許多文章標記爲收藏夾,而且一片文章能夠被許多用戶標記爲收藏夾,因此用戶與最收藏的文章之間的關係將是多對多的關係。要定義這種關係,請打開User模型並添加一個favorites()

app/User.php

注意 post模型的命名空間是 App\Models\Post
因此注意要頭部引入 use App\Models\Post;
public function favorites()
    {
        return $this->belongsToMany(Post::class, 'favorites', 'user_id', 'post_id')->withTimeStamps();
    }


第二個參數是數據透視表(收藏夾)的名稱。第三個參數是要定義關係(User)的模型的外鍵名稱(user_id),而第四個參數是要加入的模型(Post)的外鍵名稱(post_id)。

注意到咱們連接withTimeStamps()到belongsToMany()。這將容許插入或更新行時,數據透視表上的時間戳(create_at和updated_at)列將受到影響。

2.3 建立文章控制器

由於咱們以前建立過了,這裏也不須要建立了。

若是你沒有建立過,請執行 php artisan make:controller ArticleController

2.4 在文章控制器添加favoritePostunFavoritePost兩個方法

注意要頭部要引入 use Illuminate\Support\Facades\Auth;
<?php
​
namespace App\Http\Controllers;
​
use Illuminate\Http\Request;
use App\Models\Post;
​
use Illuminate\Support\Facades\Auth;
​
class ArticleController extends Controller
{
    public function index()
    {
        $data = Post::paginate(5);
        return view('home.article.index', compact('data'));
    }
​
    public function show($id)
    {
        $data = Post::find($id);
        return view('home.article.list', compact('data'));
    }
​
    public function favoritePost(Post $post)
    {
        Auth::user()->favorites()->attach($post->id);
        return back();
    }
​
    public function unFavoritePost(Post $post)
    {
        Auth::user()->favorites()->detach($post->id);
        return back();
    }
}

2.5 集成axios模塊

  • 安裝axios

npm install axios --save

  • 引入axios模塊

resource/assets/js/bootstrap.js
在最後加入

import axios from 'axios';
window.axios = axios;

2.6 建立收藏夾組件

// resources/assets/js/components/Favorite.vue
​
<template>
    <span>
        <a href="#" v-if="isFavorited" @click.prevent="unFavorite(post)">
            <i  class="fa fa-heart"></i>
        </a>
        <a href="#" v-else @click.prevent="favorite(post)">
            <i  class="fa fa-heart-o"></i>
        </a>
    </span>
</template>
​
<script>
    export default {
        props: ['post', 'favorited'],
​
        data: function() {
            return {
                isFavorited: '',
            }
        },
​
        mounted() {
            this.isFavorited = this.isFavorite ? true : false;
        },
​
        computed: {
            isFavorite() {
                return this.favorited;
            },
        },
​
        methods: {
            favorite(post) {
                axios.post('/favorite/'+post)
                    .then(response => this.isFavorited = true)
                    .catch(response => console.log(response.data));
            },
​
            unFavorite(post) {
                axios.post('/unfavorite/'+post)
                    .then(response => this.isFavorited = false)
                    .catch(response => console.log(response.data));
            }
        }
    }
</script>

2.7 視圖中引入組件

在視圖組件使用以前,咱們先引入字體文件
resource/views/layouts/app.blade.php
頭部引入字體文件

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />


並在app.blade.php
添加個人收藏夾連接

// 加在logout-form以後
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
    {{ csrf_field() }}
</form>
​
<a href="{{ url('my_favorites') }}">個人收藏夾</a>


使用組件

// resources/views/home/article/index.blade.php
​
if (Auth::check())
    <div class="panel-footer">
        <favorite
            :post={{ $list->id }}
            :favorited={{ $list->favorited() ? 'true' : 'false' }}
        ></favorite>
    </div>
endif


而後咱們要建立favorited()
打開app/Models/Post.php增長favorited()方法

注意要在頭部引用命名空間
use App\Models\Favorite;
use Illuminate\Support\Facades\Auth;
public function favorited()
    {
        return (bool) Favorite::where('user_id', Auth::id())
                            ->where('post_id', $this->id)
                            ->first();
    }

2.8 使用組件

引入Favorite.vue組件
resources/assets/js/app.js

Vue.component('favorite', require('./components/Favorite.vue'));


編譯

npm run dev


3

效果圖

效果圖1

3. 完成個人收藏夾

3.1 建立用戶控制器

php artisan make:controller UsersController


修改app/Http/Controllers/UsersController.php

<?php
​
namespace App\Http\Controllers;
​
use Illuminate\Http\Request;
​
use Illuminate\Support\Facades\Auth;
​
class UsersController extends Controller
{
    public function myFavorites()
    {
        $myFavorites = Auth::user()->favorites;
        return view('users.my_favorites', compact('myFavorites'));
    }
}


添加視圖文件

// resources/views/users/my_favorites.blade.php
​
extends('layouts.app')
​
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="page-header">
                <h3>My Favorites</h3>
            </div>
            @forelse ($myFavorites as $myFavorite)
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <a href="/article/{{ $myFavorite->id }}">
                            {{ $myFavorite->title }}
                        </a>
                    </div>
​
                    <div class="panel-body" style="max-height:300px;overflow:hidden;">
                        <img src="/uploads/{!! ($myFavorite->cover)[0] !!}" style="max-width:100%;overflow:hidden;" alt="">
                    </div>
                    @if (Auth::check())
                        <div class="panel-footer">
                            <favorite
                                :post={{ $myFavorite->id }}
                                :favorited={{ $myFavorite->favorited() ? 'true' : 'false' }}
                            ></favorite>
                        </div>
                    @endif
                </div>
            @empty
                <p>You have no favorite posts.</p>
            @endforelse
         </div>
    </div>
</div>
@endsection


而後從新向一下根目錄
routes/web.php 添加一條路由

Route::get('/', 'ArticleController@index');


最後效果圖
效果圖2

參考資料
Implement a Favoriting Feature Using Laravel and Vue.js
laravel 5.4 vue 收藏文章
github地址 https://github.com/pandoraxm/laravel-vue-favorites
原文連接 https://www.bear777.com/blog/laravel5-3-vue
相關文章
相關標籤/搜索