使用Laravel和Vue.js实现收藏夹功能

These days, various web applications are in one way or the other implementing a kind of favorite/like/recommend feature on the websites. These can be seen on sites like Medium, Facebook, Laracasts, and even here on scotch.io and school.scotch.io.

如今,各种Web应用程序都以一种方式或另一种方式在网站上实现一种“喜欢/喜欢/推荐”功能。 这些内容可以在Medium,Facebook,Laracasts等网站上看到,甚至在scotch.ioschool.scotch.io上也可以看到。

In this tutorial, I'll be showing you how to implement a favorites feature using Vue.js in your Laravel application. Though we'll be using the term favorites in this tutorial, this can be replaced with likes, recommends depending on your application.

在本教程中,我将向您展示如何在Laravel应用程序中使用Vue.js实现收藏夹功能。 尽管在本教程中我们将使用“ 收藏夹 ”一词,但可以根据喜欢的应用程序将其替换为“ likes”推荐)

我们将要建设的 ( What We'll Be Building )

We'll be building a simple Posts app. This app will comprise of users and posts. Users will be able to create posts and as well mark posts as favorites. Finally, users will be able to see all the posts they marked as favorites.

我们将构建一个简单的Posts应用程序。 该应用程序将包含用户和帖子。 用户将能够创建帖子并将帖子标记为收藏。 最后,用户将能够看到他们标记为收藏的所有帖子。

The app will have a User model and a Post model, there will be an authentication system which will allow only authenticated users mark/unmark posts as favorites. We'll make use of VueJs and Axios to make marking/un-marking posts as favorites dynamic, that is without reloading the page.

该应用程序将具有用户模型和帖子模型,还将有一个身份验证系统,该系统仅允许经过身份验证的用户将帖子标记/取消标记为收藏。 我们将利用VueJ和Axios使动态标记/取消标记为收藏夹的帖子动态化,即无需重新加载页面。

Before we start building, let's take a quick look at what the Posts app will look like when we are done.

在开始构建之前,让我们快速看一下完成后的Posts应用程序。

让我们开始吧 ( Let's Get started )

We'll start by creating a new Laravel project, the name of the project will be laravel-vue-favorite.

我们将从创建一个新的Laravel项目开始,该项目的名称将为laravel-vue-favorite

laravel new laravel-vue-favorite

This will create a new Laravel 5.4 (which is the current version as at the time of this tutorial) project.

这将创建一个新的Laravel 5.4(这是本教程时的当前版本)项目。

安装NPM依赖项 ( Installing NPM Dependencies )

In a fresh installation of Laravel, Laravel provides some frontend frameworks and libraries with some basic setup to integrate these packages together. Among the frameworks and libraries are Bootstrap, VueJs and Axios, which we will be using in this tutorial. But we still need to install these dependencies through NPM:

在Laravel的全新安装中,Laravel提供了一些前端框架和库以及一些基本设置,以将这些软件包集成在一起。 在框架和库中有BootstrapVueJsAxios ,我们将在本教程中使用它们。 但是我们仍然需要通过NPM安装这些依赖项:

npm install

Also, we'll make use of Laravel Mix to compile and build our CSS and JavaScript. The command above will also install all Laravel Mix dependencies.

另外,我们将使用Laravel Mix来编译和构建CSS和JavaScript。 上面的命令还将安装所有Laravel Mix依赖项。

模型与迁移 ( Models And Migrations )

For our Posts app, we'll need a User model (which comes with Laravel), a Post model and a Favorite model and their respective migration files.

对于我们的Posts应用程序,我们需要一个User模型(Laravel随附),一个Post模型和一个Favorite模型以及它们各自的迁移文件。

php artisan make:model Post -m
php artisan make:model Favorite -m

These will create a Post model and a Favorite model along with their migration files respectively. Open the posts table migration file and update the up() with:

这些将分别创建一个Post模型和一个Favorite模型及其迁移文件。 打开posts表迁移文件,并使用以下命令更新up()

/**
 * Define posts table schema
 */
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

The posts table will contain an id, user_id (ID of the user that created the post), title, body, and some timestamps columns.

posts表将包含一个iduser_id (创建该帖子的用户的ID), titlebody和一些timestamps列。

Next, open the favorites table migration file and update the up() with:

接下来,打开“ favorites表迁移文件,并使用以下命令更新up()

/**
 * Define favorites table schema
 */
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 will be a pivot table. It will contain two columns: user_id which will hold the ID of the user that favorited a post and post_id which will the ID of the post that was favorited.

favorites表将是数据透视表。 它包含两列: user_id将保存喜欢的帖子的用户的ID,而post_id将保存喜欢的帖子的ID。

For the users table migration, we'll be using the default Laravel provided.

对于users表迁移,我们将使用提供的默认Laravel。

Before we run our migrations, let's setup our database. Add your database details to the .env file:

在运行迁移之前,让我们设置数据库。 将数据库详细信息添加到.env文件:

DB_DATABASE=laravue
DB_USERNAME=root
DB_PASSWORD=root

Remember to update with your own database details. Now we can go on and run our migrations:

请记住使用您自己的数据库详细信息进行更新。 现在我们可以继续进行迁移了:

php artisan migrate

数据库播种器 ( Database Seeder )

We'll also generate some seed data which we can test our app with. To generate dummy data, we'll make use of Laravel Model Factories. Laravel model factories make use of the Faker PHP library.

我们还将生成一些种子数据,可以用来测试我们的应用程序。 为了生成虚拟数据,我们将使用Laravel模型工厂 。 Laravel模型工厂使用Faker PHP库。

We'll generate dummy data of Users and Posts. When you open the database/factories/ModelFactory.php file, you will see that Laravel provides a User model factory, which means we only need to create a Post model factory. Add the snippets below to database/factories/ModelFactory.php just after the User model factory:

我们将生成用户和帖子的虚拟数据。 当您打开database/factories/ModelFactory.php文件时,您会看到Laravel提供了一个User模型工厂,这意味着我们只需要创建一个Post模型工厂。 在User模型工厂之后,将以下代码段添加到database/factories/ModelFactory.php

// database/factories/ModelFactory.php

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    // Get a random user
    $user = \App\User::inRandomOrder()->first();

    // generate fake data for post
    return [
        'user_id' => $user->id,
        'title' => $faker->sentence,
        'body' => $faker->text,
    ];
});

Let's quickly run through the code. Remember from our posts table migration, we defined that a post must have a user ID. So, we get a random user and assign the user_id of a post to the ID of the random user, then we use Faker to generate the title and body of the post.

让我们快速浏览一下代码。 请记住,在我们的帖子表迁移中,我们定义了帖子必须具有用户ID。 因此,我们得到一个随机用户,并将帖子的user_id分配给随机用户的ID,然后使用Faker生成帖子的titlebody

With our model factories done, let's move on to create our database seeder classes by running these commands:

完成我们的模型工厂后,让我们继续通过运行以下命令来创建数据库种子程序类:

php artisan make:seeder UsersTableSeeder
php artisan make:seeder PostsTableSeeder

Open database/seeds/UsersTableSeeder.php and update the run() with:

打开database/seeds/UsersTableSeeder.php并使用以下命令更新run()

// database/seeds/UsersTableSeeder.php

/**
 * Run the database seeds to create users.
 *
 * @return void
 */
public function run()
{
    factory(App\User::class, 5)->create();
}

This will create 5 different users with dummy data when the seeder is run. We'll do the same for Posts. Open database/seeds/PostsTableSeeder.php and update the run() with:

运行播种机时,这将创建5个具有伪数据的不同用户。 我们将对Posts执行相同的操作。 打开database/seeds/PostsTableSeeder.php并使用以下命令更新run()

// database/seeds/PostsTableSeeder.php

/**
 * Run the database seeds to create posts.
 *
 * @return void
 */
public function run()
{
    factory(App\Post::class, 10)->create();
}

This will create 10 different posts with dummy data when the seeder is run.

当播种机运行时,这将创建10个带有虚拟数据的不同帖子。

Before we run the database seeders, let's update the database/seeds/DatabaseSeeder.php which is provided by default:

在运行数据库database/seeds/DatabaseSeeder.php之前,让我们更新默认提供的database/seeds/DatabaseSeeder.php

// database/seeds/DatabaseSeeder.php

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $this->call(UsersTableSeeder::class);
    $this->call(PostsTableSeeder::class);
}

Now we can run the database seeders:

现在我们可以运行数据库播种器:

php artisan db:seed

You should now see some dummy data in your database.

现在,您应该在数据库中看到一些虚拟数据。

验证用户 ( Authenticating Users )

Before a user can mark a post has favorite, the user must be logged in. So we need a kind of authentication system. Luckily for us, Laravel got our back on this. We'll use the artisan make:auth command to scaffold an authentication system.

用户必须先登录,然后用户才能标记帖子中的收藏夹。因此,我们需要一种身份验证系统。 对我们来说幸运的是,Laravel对此表示了支持。 我们将使用artisan make:auth命令来构建身份验证系统。

php artisan make:auth

This will create all of the necessary routes and views for authentication. We can go and register as a user, which we will use to test the functionality of the application we are building.

这将创建用于身份验证的所有必要路由和视图。 我们可以注册为用户,然后将其用于测试正在构建的应用程序的功能。

定义路线 ( Defining Our Routes )

Let's define the routes of our application. Open routes/web.php and update with below:

让我们定义应用程序的路由。 打开routes/web.php并使用以下内容进行更新:

// routes/web.php

Auth::routes();

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

Route::post('favorite/{post}', 'PostsController@favoritePost');
Route::post('unfavorite/{post}', 'PostsController@unFavoritePost');

Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');

The routes are pretty straightforward. Auth routes that Laravel created when we ran the make:auth command. A route to the homepage that will list all posts, two other routes for favoriting and unfavoriting posts. Lastly, a route that displays all posts that have been marked as favorites by a user. This route will be accessible to only authenticated users.

路线非常简单。 Laravel运行make:auth命令时创建的Auth路由。 到首页的路线,其中列出了所有帖子,另外两条路线是收藏和不喜欢的帖子。 最后,一条路线显示所有被用户标记为收藏夹的帖子。 只有经过身份验证的用户才能访问此路由。

When a user registers or login, Laravel will redirect them to the /home route by default. Since we have removed the /home route that Laravel created when we ran make:auth. We need to update the redirectTo property of both app/Http/Controllers/Auth/LoginController.php and app/Http/Controllers/Auth/RegisterController.php to:

用户注册或登录时,Laravel默认会将其重定向到/home路由。 由于我们删除了运行make:auth时Laravel创建的/home路由。 我们需要将app/Http/Controllers/Auth/LoginController.phpapp/Http/Controllers/Auth/RegisterController.phpredirectTo属性更新为:

protected $redirectTo = '/';

定义用户最喜欢的帖子关系 ( Defining Users To Favorite Posts Relationship )

Since a user can mark many posts as favorites and a post can be marked as favorites by many users, the relationship between users and favorite posts will be a many to many relationships. To define this relationship, open the User model and add a favorites():

由于用户可以将许多帖子标记为收藏夹,并且很多用户可以将帖子标记为收藏夹,因此用户和收藏夹帖子之间的关系将是多对多关系。 要定义这种关系,请打开“ User模型并添加一个favorites()

// app/User.php

/**
 * Get all of favorite posts for the user.
 */
public function favorites()
{
    return $this->belongsToMany(Post::class, 'favorites', 'user_id', 'post_id')->withTimeStamps();
}

Laravel will assume the pivot table is post_user but since we gave the pivot table a different name (favorites), we have to pass in some additional arguments. The second argument is the name of the pivot table (favorites). The third argument is the foreign key name (user_id) of the model on which you are defining the relationship (User), while the fourth argument is the foreign key name (post_id) of the model that you are joining to (Post).

Laravel将假定数据透视表为post_user但是由于我们为数据透视表指定了其他名称(收藏夹),因此我们必须传递一些其他参数。 第二个参数是数据透视表的名称(收藏夹)。 第三个参数是您要在其上定义关系(User)的模型的外键名称(user_id),而第四个参数是您要加入(Post)的模型的外键名称(post_id)。

Noticed we chained withTimeStamps() to the belongsToMany(). This will allow the timestamps (create_at and updated_at) columns on the pivot table be affected whenever a row is inserted or updated.

注意,我们使用withTimeStamps()将其链接到belongsToMany() 。 每当插入或更新一行时,这将使数据透视表上的时间戳记列( create_atupdated_at )受到影响。

职位控制器 ( Posts Controller )

Let's create a new controller that will handle displaying posts, marking a post as favorite and unfavorite a post.

让我们创建一个新的控制器来处理显示的帖子,将帖子标记为收藏和不收藏。

php artisan make:controller PostsController

Open the newly created app/Http/Controllers/PostsController.php and add the snippet below to it:

打开新创建的app/Http/Controllers/PostsController.php并将以下代码段添加到其中:

// app/Http/Controllers/PostsController.php

// remember to use the Post model
use App\Post;

/**
 * Display a paginated list of posts.
 *
 * @return Response
 */
public function index()
{
    $posts = Post::paginate(5);

    return view('posts.index', compact('posts'));
}

The index() will get all posts and paginate them into 5 per page. Then render a view file (that we are yet to create) along with the posts, which will do the actual displaying of the posts.

index()将获取所有帖子并将其分页为每页5个。 然后将视图文件(我们尚未创建)与帖子一起渲染,这将实际显示帖子。

Remember when we ran make:auth command that Laravel created some views. We'll be using the resources/views/layouts/app.blade.php that was created and make some few additions to it. Add the code below just after the <title>:

请记住,当我们运行make:auth命令时,Laravel创建了一些视图。 我们将使用创建的resources/views/layouts/app.blade.php并对其进行一些补充。 在<title>之后添加以下代码:

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

Then add this just before the Logout list item:

然后将其添加到“ Logout列表项之前:

// resources/views/layouts/app.blade.php<li>
    <a href="{{ url('my_favorites') }}">My Favorites</a>
</li>

Now let's create the index view. Create a new posts folder within views directory and create a new index.blade.php file within the newly created folder. Paste the code below into resources/views/posts/index.blade.php:

现在让我们创建index视图。 在views目录中创建一个新的posts文件夹,并在新创建的文件夹中创建一个新的index.blade.php文件。 将以下代码粘贴到resources/views/posts/index.blade.php

// resources/views/posts/index.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>All Posts</h3>
            </div>
            @forelse ($posts as $post)
                <div class="panel panel-default">
                    <div class="panel-heading">
                        {{ $post->title }}
                    </div>

                    <div class="panel-body">
                        {{ $post->body }}
                    </div>
                </div>
            @empty
                <p>No post created.</p>
            @endforelse

            {{ $posts->links() }}
        </div>
    </div>
</div>
@endsection

Pretty simple markup that displays a paginated list of posts. Open the homepage in your browser, you should see page like the image below:

非常简单的标记,显示分页的帖子列表。 在浏览器中打开主页,您应该看到如下图所示的页面:

Next, let's go back to PostsController and add the methods that will handle marking a post as favorite and unfavorite a post. Add the code below to PostsController:

接下来,让我们回到PostsController并添加用于将帖子标记为收藏和不收藏的方法。 将以下代码添加到PostsController

// app/Http/Controllers/PostsController.php

// remember to use
use Illuminate\Support\Facades\Auth;

/**
 * Favorite a particular post
 *
 * @param  Post $post
 * @return Response
 */
public function favoritePost(Post $post)
{
    Auth::user()->favorites()->attach($post->id);

    return back();
}

/**
 * Unfavorite a particular post
 *
 * @param  Post $post
 * @return Response
 */
public function unFavoritePost(Post $post)
{
    Auth::user()->favorites()->detach($post->id);

    return back();
}

The favoritePost() takes a post as an argument. Using the favorites relationship we defined above, we attach the post ID to the ID of the authenticated user then insert into the favorites table. Finally, return back to the previous page.

favoritePost()将帖子作为参数。 使用上面定义的favorites关系,我们将帖子ID附加到已验证用户的ID上,然后插入favorites表中。 最后,返回上一页。

The unFavoritePost() is the reverse of favoritePost() which simply remove the ID of the authenticated user along with the post ID from the favorites table.

unFavoritePost()favoritePost()相反,后者只是从favorites表中删除经过身份验证的用户的ID和帖子ID。

与VueJs集成 ( Integrating With VueJs )

It's time to integrate Vue into our application. We'll make the favorite button/icon a Vue component. Making it a Vue component will allow for reuse in multiple places with our application.

现在是时候将Vue集成到我们的应用程序中了。 我们将使收藏夹按钮/图标成为Vue组件。 使其成为Vue组件将允许我们的应用程序在多个地方重复使用。

Once the favorite button/icon is clicked, we'll mark the post as favorite or unfavorite without reloading the page, that is through AJAX. For this, we'll make use of Axios which is a Promise based HTTP client for the browser and node.js.

单击收藏夹按钮/图标后,我们将通过AJAX将帖子标记为收藏或不收藏,而无需重新加载页面。 为此,我们将使用Axios ,它是基于Promise的HTTP客户端,用于浏览器和node.js。

创建收藏夹组件 ( Creating The Favorite Component )

Create a new Favorite.vue file within the resources/assets/js/components folder and paste the code below into it:

resources/assets/js/components文件夹中创建一个新的Favorite.vue文件,并将以下代码粘贴到其中:

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

The Favorite component has two sections: template and script. In the template section, we defined the markup that will be rendered when the component is used. We are using conditional rendering to show the appropriate button/icon. That is, if isFavorited is true, the button/icon should be marked as favorite and on click of the button/icon should trigger unFavorite(). Else the button/icon should be marked as unfavorite and on click of the button/icon should trigger favorite().

Favorite组件有两个部分: templatescript 。 在template部分,我们定义了将在使用组件时呈现的标记。 我们使用条件渲染来显示适当的按钮/图标。 也就是说,如果isFavoritedtrue ,则按钮/图标应标记为收藏,并且在单击按钮/图标时应触发unFavorite() 。 否则,按钮/图标应标记为“收藏夹”,并且单击按钮/图标后应触发“ favorite()

Moving on to the script section, we defined some properties for the component; post (will be the ID of the post) and favorited (will either be true or false depending on if the post has been favorited by the authenticated user). We also defined an isFavorited data which will be used for the conditional rendering from above.

继续到script部分,我们为组件定义了一些属性。 post (将是post的ID)并被favorited (根据验证过的用户是否喜欢该帖子,则为truefalse )。 我们还定义了一个isFavorited数据,该数据将用于从上方进行条件渲染。

When the component is mounted, we set the value of isFavorited to the value of isFavorite computed property. That is, the isFavorite computed property will return the value of favorited prop which will either be true or false. We use a computed property so as to reactively get the value of the favorited prop instead using the value of favorited prop that was passed directly.

装入组件时,我们将isFavorited的值设置为isFavorite计算属性的值。 也就是说, isFavorite计算属性将返回truefalsefavorited prop的值。 我们使用计算属性,以便React性地获取favorited道具的值,而不是使用直接传递的favorited道具的值。

Lastly, we defined two methods: favorite() and unFavorite() which both accepts the post prop as arguments. Using Axios, we make a POST request to the routes we defined earlier. For the favorite(), once the POST request is successful, we set isFavorited to true and otherwise console log the errors. Same is applicable to the unFavorite() just that we set isFavorited to false.

最后,我们定义了两个方法: favorite()unFavorite() ,它们都接受post unFavorite()作为参数。 使用Axios ,我们向先前定义的路由发出POST请求。 对于favorite() ,一旦POST请求成功,我们将isFavorited设置为true ,否则控制台记录错误。 只需将isFavorited设置为false ,同样适用于unFavorite()

注册收藏夹组件 ( Registering The Favorite Component )

Before we can start to use the Favorite component, we need to first register it on our Vue root instance. Open resources/assets/js/app.js, you will see that Laravel register an Example component. We are going to replace that with the Favorite component:

在开始使用Favorite组件之前,我们需要先在Vue根实例上注册它。 打开resources/assets/js/app.js ,您将看到Laravel注册了一个Example组件。 我们将用“ Favorite组件替换它:

// resources/assets/js/app.js

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

Now we can compile and build our styles and scripts:

现在,我们可以编译和构建样式和脚本:

npm run dev

使用收藏夹组件 ( Using The Favorite Component )

We can now use the Favorite component. Open resources/views/posts/index.blade.php and add the snippets below to it after the closing div of the panel-body:

现在,我们可以使用Favorite组件。 打开resources/views/posts/index.blade.php并在panel-body div结束后添加以下代码片段:

// resources/views/posts/index.blade.php

@if (Auth::check())
    <div class="panel-footer">
        <favorite
            :post={{ $post->id }}
            :favorited={{ $post->favorited() ? 'true' : 'false' }}
        ></favorite>
    </div>
@endif

The favorite button/icon will only be displayed to authenticated users. As you can see, we passed to the Favorite component the props that we defined when we created the component. To know if a post is has been favorited by the authenticated user, we call a favorited() (which we are yet to create) on the post.

收藏夹按钮/图标将仅显示给经过身份验证的用户。 如您所见,我们将创建组件时定义的道具传递给了Favorite组件。 要知道已通过身份验证的用户是否喜欢某个帖子,我们可以在该帖子上调用favorited() (我们尚未创建)。

To create favorited(), open app/Post.php and add the code below to it:

要创建app/Post.php favorited() ,请打开app/Post.php并将以下代码添加到其中:

// app/Post.php

// remember to use
use App\Favorite;
use Illuminate\Support\Facades\Auth;

/**
 * Determine whether a post has been marked as favorite by a user.
 *
 * @return boolean
 */
public function favorited()
{
    return (bool) Favorite::where('user_id', Auth::id())
                        ->where('post_id', $this->id)
                        ->first();
}

This gets and casts to boolean the first result where the user_id is equal to that of the authenticated user and where the post_id is equal to the ID of the post the method is called on.

这将获取并强制转换为boolean的第一个结果,其中user_id等于已验证用户的结果,并且post_id等于调用该方法的帖子的ID。

If you visit the homepage of the application in the browser and login, you should get something similar to:

如果您在浏览器中访问该应用程序的主页并登录,则应该获得类似于以下内容的信息:

As you can see I have marked some posts as favorites.

如您所见,我已将某些帖子标记为收藏。

显示用户喜欢的帖子 ( Displaying User Favorite Posts )

Won't it be nice for users to be able to see all the posts they have marked as favorites? Sure it will be. Remember we defined a my_favorites route that will be accessible to only authenticated users, this is where users will be able to see the posts they've marked as favorites.

用户能够看到他们标记为收藏的所有帖子,这会很好吗? 当然可以。 记住,我们定义了一个my_favorites路由,只有经过身份验证的用户才能访问该路由,在my_favorites路由中,用户将能够看到他们将其标记为收藏的帖子。

Let's create a UsersController that will handle this route.

让我们创建一个处理此路由的UsersController

php artisan make:controller UsersController

Open app/Http/Controllers/UsersController.php and add the code below to it:

打开app/Http/Controllers/UsersController.php并添加以下代码:

// app/Http/Controllers/UsersController.php

// remember to use
use Illuminate\Support\Facades\Auth;

/**
 * Get all favorite posts by user
 *
 * @return Response
 */
public function myFavorites()
{
    $myFavorites = Auth::user()->favorites;

    return view('users.my_favorites', compact('myFavorites'));
}

The myFavorites() uses the favorites relationship we defined earlier, get all the posts that the authenticated user has marked as favorites. Then return a view along with favorites posts.

myFavorites()使用我们之前定义的favorites关系,获取通过身份验证的用户已将其标记为收藏夹的所有帖子。 然后返回一个视图以及收藏夹帖子。

Now let's create the view. Create a new users folder within the resources/views directory and within the users folder, create a new file my_favorites.blade.php and paste the code below to it:

现在让我们创建视图。 创建一个新的users文件夹内resources/views目录中的users文件夹中创建一个新的文件my_favorites.blade.php和粘贴下面的代码吧:

// 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">
                        {{ $myFavorite->title }}
                    </div>

                    <div class="panel-body">
                        {{ $myFavorite->body }}
                    </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

The markup is similar to that of index.blade.php. As you can see, we also used the Favorite component. When viewed in the browser, you should see something similar to:

标记类似于index.blade.php的标记。 如您所见,我们还使用了Favorite组件。 在浏览器中查看时,您应该看到类似于以下内容:

结论 ( Conclusion )

That's it, we are done building the Post app and seen how to allow only authenticated users mark/unmark posts as favorites without reloading the page using VueJs and Axios. I hope you find this tutorial useful. If you encounter any problems following this tutorial or have questions/suggestions, kindly drop them in the comment section below. Also, I have made a vue-favorite component based on this tutorial which can be installed through NPM.

就这样,我们完成了Post应用程序的构建,并介绍了如何仅允许经过身份验证的用户将帖子标记/取消标记为收藏夹,而无需使用VueJs和Axios重新加载页面。 希望本教程对您有所帮助。 如果您在本教程之后遇到任何问题或有疑问/建议,请将其放在下面的评论部分。 另外,我根据本教程制作了一个vue-favorite组件,可以通过NPM安装。

翻译自: https://scotch.io/tutorials/implement-a-favoriting-feature-using-laravel-and-vue-js

  • 0
    点赞
  • 1
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值