0

0

用laravel5.3 vue做出收藏夹功能

php中世界最好的语言

php中世界最好的语言

发布时间:2018-04-13 11:51:14

|

1683人浏览过

|

来源于php中文网

原创

这次给大家带来用laravel5.3 vue做出收藏夹功能,用laravel5.3 vue做出收藏夹功能的注意事项有哪些,下面就是实战案例,一起来看一下。

以下便是laravel5.3 vue 实现收藏夹功能的实例代码

{
 "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');

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'

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

1.1 安装npm 模块

(如果之前没有执行此操作)

npm  install

laravel5.3 vue 怎么实现收藏夹功能 

1.2 创建模型及迁移

我们需要一个User模型(laravel附带),一个Post模型和一个Favorite模型以及它们各自的迁移文件。 因为我们之前创建过了 Post 的模型,所以我们只需要创建一个 Favorite 模型即可。

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

这会创建一个 Favorite

模型以及迁移文件。

1.3 修改 posts 迁移表及 favorites 的 up 方法

给 posts 表在 id 字段后面新增一个 user_id 字段

php artisan make:migration add_userId_to_posts_table --table=posts

修改 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();
 });
 }

该 favorites 表包含两列:

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 模型的命名空间是 AppModelsPost 所以注意要头部引入 use AppModelsPost;

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 在文章控制器添加 favoritePost 和 unFavoritePost 两个方法

注意要头部要引入 use IlluminateSupportFacadesAuth;

<?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="#" 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 视图中引入组件

在视图组件使用之前,我们先引入字体文件 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') }}" rel="external nofollow" >我的收藏夹</a>

使用组件

// 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>

endif

然后我们要创建 favorited() 打开 app/Models/Post.php 增加 favorited() 方法

注意要在头部引用命名空间 use AppModelsFavorite; use IlluminateSupportFacadesAuth;

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. 完成 我的收藏夹

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')
<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- alt="用laravel5.3 vue做出收藏夹功能" >cover)[0] !!}"   style="max-width:90%" 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

然后重新向一下根目录 routes/web.php 添加一条路由

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

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Angular17里的自定义指令使用详解

Ztoy网络商铺多用户版
Ztoy网络商铺多用户版

在原版的基础上做了一下修正:增加1st在线支付功能与论坛用户数据结合,vip也可与论坛相关,增加互动性vip会员的全面修正评论没有提交正文的问题特价商品的调用连接问题删掉了2个木马文件去掉了一个后门补了SQL注入补了一个过滤漏洞浮动价不能删除的问题不能够搜索问题收藏时放入购物车时出错点放入购物车弹出2个窗口修正定单不能删除问题VIP出错问题主题添加问题商家注册页导航连接问题添加了导航FLASH源文

下载

立即学习前端免费学习笔记(深入)”;

JS里EventLoop的使用详解

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
laravel组件介绍
laravel组件介绍

laravel 提供了丰富的组件,包括身份验证、模板引擎、缓存、命令行工具、数据库交互、对象关系映射器、事件处理、文件操作、电子邮件发送、队列管理和数据验证。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

332

2024.04.09

laravel中间件介绍
laravel中间件介绍

laravel 中间件分为五种类型:全局、路由、组、终止和自定。想了解更多laravel中间件的相关内容,可以阅读本专题下面的文章。

285

2024.04.09

laravel使用的设计模式有哪些
laravel使用的设计模式有哪些

laravel使用的设计模式有:1、单例模式;2、工厂方法模式;3、建造者模式;4、适配器模式;5、装饰器模式;6、策略模式;7、观察者模式。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

601

2024.04.09

thinkphp和laravel哪个简单
thinkphp和laravel哪个简单

对于初学者来说,laravel 的入门门槛较低,更易上手,原因包括:1. 更简单的安装和配置;2. 丰富的文档和社区支持;3. 简洁易懂的语法和 api;4. 平缓的学习曲线。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

380

2024.04.10

laravel入门教程
laravel入门教程

本专题整合了laravel入门教程,想了解更多详细内容,请阅读专题下面的文章。

131

2025.08.05

laravel实战教程
laravel实战教程

本专题整合了laravel实战教程,阅读专题下面的文章了解更多详细内容。

81

2025.08.05

laravel面试题
laravel面试题

本专题整合了laravel面试题相关内容,阅读专题下面的文章了解更多详细内容。

69

2025.08.05

resource是什么文件
resource是什么文件

Resource文件是一种特殊类型的文件,它通常用于存储应用程序或操作系统中的各种资源信息。它们在应用程序开发中起着关键作用,并在跨平台开发和国际化方面提供支持。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

169

2023.12.20

pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法

本专题系统整理pixiv网页版官网入口及登录访问方式,涵盖官网登录页面直达路径、在线阅读入口及快速进入方法说明,帮助用户高效找到pixiv官方网站,实现便捷、安全的网页端浏览与账号登录体验。

561

2026.02.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
前端JS开发27个经典实战视频教程
前端JS开发27个经典实战视频教程

共34课时 | 11.9万人学习

Node.js 教程
Node.js 教程

共57课时 | 11.5万人学习

PostgreSQL 教程
PostgreSQL 教程

共48课时 | 9.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号