Home Web Front-end JS Tutorial laravel5.3 vue implements favorites function

laravel5.3 vue implements favorites function

Jan 24, 2018 am 10:42 AM
Function Favorites

The author of this article introduces laravel5.3 vue to implement the favorites function. This article introduces it to you in great detail through example code. Friends who need it can refer to it. I hope it can help you.

This article will introduce you to 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"
 }
}
Copy after login

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');
});
Copy after login

1.0.3 Modify resource/assets/js/app .js

Change the original el: 'body' to el: '#app'

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

1.1 Install npm module

(If you have not executed this before Operation)

npm install

1.2 Create model and migration

We need a User model (included with laravel), a Post model and a Favorite model with their respective migration files. Because we have created a Post model before, we only need to create a Favorite model.

php artisan make:model App\Models\Favorite -m
Copy after login

This will create a Favorite

model and migration file.

1.3 Modify the up method of posts migration table and favorites

Add a user_id field after the id field to the posts table

php artisan make:migration add_userId_to_posts_table --table=posts
Copy after login

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();
 });
 }
Copy after login

The favorites table contains two columns:

user_id The user ID of the collected article.

post_id The ID of the collected post.

Then perform table migration

php artisan migrate

1.4 User authentication

Because we have already created it before, so there is no need here Need to be created again.

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

2. Complete the favorites function

Modify routes/web.php

2.1 Create router

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

2.2 Many-to-many relationship between articles and users

Because users can mark many articles as favorites, and an article can be marked as favorites by many users Favorites, so the relationship between the user and the most favorited articles will be a many-to-many relationship. 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, so be sure to introduce use App\Models\ in the header Post;

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

The second parameter is the name of the pivot table (favorite). The third parameter is the foreign key name (user_id) of the model to define the relationship (User), and the fourth parameter is the foreign key name (post_id) of the model (Post) to be added. Notice that we link withTimeStamps() to belongsToMany(). This will allow when a row is inserted or updated, the timestamp (create_at and updated_at) columns on the pivot table will be affected.

2.3 Create article controller

Because we have created it before, there is no need to create it here.

If you have not created it before, please execute php artisan make:controller ArticleController

2.4 Add favoritePost and unFavoritePost two methods in the article controller

Note that the header must be introduced 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(&#39;home.article.index&#39;, compact(&#39;data&#39;));
 }
 public function show($id)
 {
 $data = Post::find($id);
 return view(&#39;home.article.list&#39;, compact(&#39;data&#39;));
 }
 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();
 }
}
Copy after login

2.5 Integrate axios module

•Install axios

npm install axios --save

•Introduce axios module resource/assets/js/bootstrap.js and add at the end

import axios from 'axios';
window.axios = axios;
Copy after login

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>
Copy after login

2.7 Introduce components into the view

Before using the view component, we first introduce the font file resource/views/layouts/app.blade.php and introduce the font file in the header

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

and add it in app.blade.php My favorites link

// 加在logout-form之后
<form id="logout-form" action="{{ url(&#39;/logout&#39;) }}" method="POST" style="display: none;">
 {{ csrf_field() }}
</form>
<a href="{{ url(&#39;my_favorites&#39;) }}" rel="external nofollow" >我的收藏夹</a>
Copy after login

Using components

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

endif

Then we need to create favorited() Open app/Models/Post.php and add favorited() Method

Note to reference the namespace in the header 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 after login

2.8 Use components

Introducing the Favorite.vue component resources/assets/js/app.js

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

Compilation

npm run dev
Copy after login

##Rendering

3. Complete my favorites

3.1 Create user controller


php artisan make:controller UsersController
Copy after login
Modify

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'));
 }
}
Copy after login
Add view file

// resources/views/users/my_favorites.blade.php

extends('layouts.app')

@section('content')
<p class="container">
 <p class="row">
 <p class="col-md-8 col-md-offset-2">
  <p class="page-header">
  <h3>My Favorites</h3>
  </p>
  @forelse ($myFavorites as $myFavorite)
  <p class="panel panel-default">
   <p class="panel-heading">
   <a href="/article/{{ $myFavorite->id }}" rel="external nofollow" >
    {{ $myFavorite->title }}
   </a>
   </p>

   <p class="panel-body" style="max-height:300px;overflow:hidden;">
   <img src="/uploads/{!! ($myFavorite->cover)[0] !!}" style="max-width:100%;overflow:hidden;" alt="">
   </p>
   @if (Auth::check())
   <p class="panel-footer">
    <favorite
    :post={{ $myFavorite->id }}
    :favorited={{ $myFavorite->favorited() ? 'true' : 'false' }}
    ></favorite>
   </p>
   @endif
  </p>
  @empty
  <p>You have no favorite posts.</p>
  @endforelse
  </p>
 </p>
</p>
@endsection
Copy after login
Then add a route to the root directory routes/web.php again

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

Final rendering

Related recommendations:

js Firefox Add Favorites Function Code Compatible with Firefox and IE_javascript Tips

JavaScript Add Favorites Function (Compatible with IE, Firefox, Chrome)_javascript Tips

Native JS implementation of adding favorites code_javascript skills

The above is the detailed content of laravel5.3 vue implements favorites function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to sort photos by favorites in Windows 11 How to sort photos by favorites in Windows 11 Mar 18, 2024 am 09:37 AM

In this article, we will explain how to sort photos using the Favorites feature in Windows 11. The Photos app in Windows offers a convenient feature that allows you to mark specific photos or videos as Favorites or Preferences. Once you mark these items as favorites, they are automatically organized into a separate folder, allowing you to easily browse your favorite content without having to hunt through your entire photo library. This feature enables you to quickly access and manage your favorite photos and videos, saving you a lot of time and effort. Normally, photos in the Favorites folder are sorted by date in descending order, so that the newest photos appear first, followed by older photos. However, if you wish to focus on

What functions does Doubao app have? What functions does Doubao app have? Mar 01, 2024 pm 10:04 PM

There will be many AI creation functions in the Doubao app, so what functions does the Doubao app have? Users can use this software to create paintings, chat with AI, generate articles for users, help everyone search for songs, etc. This function introduction of the Doubao app can tell you the specific operation method. The specific content is below, so take a look! What functions does the Doubao app have? Answer: You can draw, chat, write articles, and find songs. Function introduction: 1. Question query: You can use AI to find answers to questions faster, and you can ask any kind of questions. 2. Picture generation: AI can be used to create different pictures for everyone. You only need to tell everyone the general requirements. 3. AI chat: can create an AI that can chat for users,

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly Implement Return to Previous Page Function PHP Tips: Quickly Implement Return to Previous Page Function Mar 09, 2024 am 08:21 AM

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

What is Discuz? Definition and function introduction of Discuz What is Discuz? Definition and function introduction of Discuz Mar 03, 2024 am 10:33 AM

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

Detailed explanation of the functions and functions of GDM under Linux Detailed explanation of the functions and functions of GDM under Linux Mar 01, 2024 pm 04:18 PM

Detailed explanation of the functions and functions of GDM under Linux In the Linux operating system, GDM (GNOMEDisplayManager) is a graphical login manager that provides an interface for users to log in and log out of the system. GDM is usually part of the GNOME desktop environment, but can be used by other desktop environments as well. The role of GDM is not only to provide a login interface, but also includes user session management, screen saver, automatic login and other functions. The functions of GDM mainly include the following aspects:

See all articles