Laravel5.3 vue provides a detailed description of the favorites function instance, laravel5.3vue
The following section describes how to use laravel5.3 vue to implement the favorites function. The specific code is as follows:
{ "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 modify gulpfile. js
Change the original require ('laravel-elixir-vue '); to 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');});
1.0.3 modify resource/assets/js/app. js
Change the original el: 'body' to el: '# app'
const app = new Vue({ el: '#app'});
1.1 install the npm Module
(If you have not performed this operation before)
npm install
1.2 create models and migrate
We need a User model (included with laravel), a Post model, a Favorite model, and their respective migration files. Because we have previously created the Post model, we only need to create a Favorite model.
php artisan make:model App\Models\Favorite -m
This will create a Favorite
Models and migration files.
1.3 modify the posts migration table and the favorites up Method
Add a user_id field to the id field of the posts table.
php artisan make:migration add_userId_to_posts_table --table=posts
Modify 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'); }); }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(); }); }
The favorites table contains two columns:
User_id: the user ID of the favorite article.
The ID of the post whose post_id is added to the favorites folder.
Then perform table migration
php artisan migrate
1.4 User Authentication
Because we have already created it, we do not need to create it again here.
If you have not created a user authentication module, You need to execute php artisan make: auth
2. Complete the search folder Function
Modify routes/web. php
2.1 create a vro
Auth::routes();Route::post('favorite/{post}', 'ArticleController@favoritePost');Route::post('unfavorite/{post}', 'ArticleController@unFavoritePost');Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');
2.2 many-to-many relationship between articles and users
Because users can mark many articles as favorites and many users can mark an article as favorites, the relationship between users and favorite articles will be many-to-many. To define this relationship, open the User model and add a favorites () app/User. php
Note that the namespace of the post model is App \ Models \ Post. Therefore, you must introduce the use App \ Models \ Post header;
public function favorites() { return $this->belongsToMany(Post::class, 'favorites', 'user_id', 'post_id')->withTimeStamps(); }
The second parameter is the name of the PivotTable (favorites. The third parameter is the external key name (user_id) of the model to define the relationship (User), and the fourth parameter is the external key name (post_id) of the model (Post) to be added ). Notice that we link withTimeStamps () to belongsToMany (). This will allow insertion or update of rows, and the time stamp (create_at and updated_at) columns on the PivotTable will be affected.
2.3 create an article Controller
Because we have created it before, and we do not need to create it here.
If you have not created one, execute php artisan make: controller ArticleController
2.4 Add the favoritePost and unFavoritePost methods to the article Controller
Note that use Illuminate \ Support \ Facades \ Auth should be introduced in the header;
<?phpnamespace 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 integrate the axios Module
• Install axios
npm install axios --save
• Introduce the axios module resource/assets/js/bootstrap. js and add it to the end.
import axios from 'axios';window.axios = axios;
2.6 create a favorites component
// resources/assets/js/components/Favorite.vue<template> <span> <a href="#" rel="external nofollow" rel="external nofollow" v-if="isFavorited" @click.prevent="unFavorite(post)"> <i class="fa fa-heart"></i> </a> <a href="#" rel="external nofollow" rel="external nofollow" 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 introduce components in the view
Before using the view component, we first introduce the font file resource/views/layouts/app. blade. php header to introduce the font file.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
Add my favorites link in app. blade. php
// After logout-form, <form id = "logout-form" action = "{url ('/logout ')}} "method =" POST "style =" display: none; ">{{ csrf_field ()}} </form> <a href = "{url ('My _ favorites ')}" rel = "external nofollow"> my favorites </a>
Use Components
// resources/views/home/article/index.blade.phpif (Auth::check()) <div class="panel-footer"> <favorite :post={{ $list->id }} :favorited={{ $list->favorited() ? 'true' : 'false' }} ></favorite> </div>
Endif
Then we will create favorited () to open app/Models/Post. php and add the favorited () method.
Note that the namespace use App \ Models \ Favorite; use Illuminate \ Support \ Facades \ Auth should be referenced in the header;
public function favorited() { return (bool) Favorite::where('user_id', Auth::id()) ->where('post_id', $this->id) ->first(); }
2.8 use components
Introduce the Favorite. vue component resources/assets/js/app. js
Vue.component('favorite', require('./components/Favorite.vue'));
Compile
npm run dev
3. Complete my favorites
3.1 create a user Controller
php artisan make:controller UsersController
Modify
app/Http/Controllers/UsersController.php <?phpnamespace 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')); }}
Add View File
// resources/views/users/my_favorites.blade.phpextends('layouts.app')@section('content')<div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="page-header">
Then add a route entry to the root directory routes/web. php.
Route::get('/', 'ArticleController@index');
Last
Summary
The above is the laravel5.3 vue provided by the mini-editor to achieve the favorites function. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in time!