This article follows the use of WangEditor and multi-image uploads in Laravel (part 2), so we won’t show you how to create a new project here.

1. Laravel project installation

Download the previous project and complete the installation.

1.0 Write before

Be sure to read this section to avoid stumbling on the VUE version later

Modify the 1.0.1package.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"}}Copy the code

1.0.2 modifygulpfile.js

Replace the original require(‘ laravel-Elixir-vue ‘); Is modified to the require (‘ laravel – elixir – vue – 2 ‘);

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');
});
Copy the code

​ ​

1.0.3 modifyresource/assets/js/app.js

Change el: ‘body’ to el: ‘#app’

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

1.1 Installing the NPM Module

(If you have not done this before)

npm  install
Copy the code

1.2 Model creation and migration

We need a User model (shipped with Laravel), a Post model and a Favorite model with their respective migration files. Since we’ve created the Post model before, we just need to create a Favorite model.

php artisan make:model App\Models\Favorite -m
Copy the code

Favorite

1.3 to modifypostsThe migration andfavoritestheupmethods

Add a user_id field to posts table

php artisan make:migration add_userId_to_posts_table --table=posts
Copy the code

Modify the database/migrations / 2018 _01_18_145843_add_userid_to_posts_table. PHP

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

database/migrations/2018_01_18_142146_create_favorites_table.php

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

The Favorites table contains two columns:

User_id User ID of the favorites. Post_id Indicates the ID of a favorite post.Copy the code

Table migration is then performed

php artisan migrate
Copy the code

1.4 User Authentication

Because we’ve already created it before, we don’t need to create it again.

If you have not created a user authentication module, you need to do PHP artisan make:auth

2. The collection folder search function is complete

Modify the routes/web. PHP

2.1 Creating a Router

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

2.2 Many-to-many relationship between articles and users

Because a user can bookmark many articles, and a single article can be bookmarked by many users, the relationship between the user and the most favorite article will be many-to-many. To define this relationship, open the User model and add a Favorites () app/ user.php

Note that the post model namespace is App\Models\ POST, so be sure to introduce use App\Models\ post in the header;

    public function favorites()
    {
        return $this->belongsToMany(Post::class, 'favorites'.'user_id'.'post_id')->withTimeStamps();
    }
Copy the code

The second parameter is the name of the PivotTable (favorites). The third parameter is the foreign key name (user_id) of the model to which the relationship (User) is to be defined, and the fourth parameter is the foreign key name (post_id) of the model to be added (Post). Note that we linked withTimeStamps() to belongsToMany(). This will allow the timestamp (create_AT and UPDATed_AT) columns on the PivotTable to be affected when rows are inserted or updated.

2.3 Creating an Article Controller

Because we created it before, we don’t need to create it here.

If you haven’t already created PHP artisan make: Controller ArticleController

2.4 Add in the article controllerfavoritePostandunFavoritePostTwo methods

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 { publicfunction 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);
        returnback(); }}Copy the code

2.5 integrationaxiosThe module

  • Install axios
npm install axios --save
Copy the code

  • Introduce the AXIos moduleresource/assets/js/bootstrap.jsJoin in at the end
import axios from 'axios';
window.axios = axios;
Copy the code

2.6 Creating a Favorites Component

// 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>
Copy the code

2.7 Importing Components into a View

Before the view components used, we first introduce the font file resource/views/layouts/app. Blade. PHP head into the font file

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

Add my favorites link to app.blade.php

/ / add inlogout- after form <form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
    {{ csrf_field() }}
</form>
​
<a href="{{ url('my_favorites') }}"< p style = "max-width: 100%; clear: both; min-height: 1em;Copy the code

Using the component

// 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
Copy the code

Then we need to create favorited() and open app/Models/ post.php to add the favorited() method

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();
    }
Copy the code

2.8 Using Components

Introduce Favorite. Vue component resources/assets/js/app. Js

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

compile

npm run dev
Copy the code

3. CompleteMy favorites

3.1 Creating a User Controller

php artisan make:controller UsersController
Copy the code

Modify Http/app/Controllers/UsersController. PHP

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

Add a View file

// 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
Copy the code

Then add a new route to the root directory routes/web.php

Route::get('/'.'ArticleController@index');
Copy the code

Final rendering

Implement a Favoriting Feature Using Laravel and vue.js

Laravel 5.4 vue collection of articles

Making address github.com/pandoraxm/l…

The original link www.bear777.com/blog/larave…