[
](https://lccdn.phphub.org/uploads/images/201703/29/5698/zhloDjJo5G.gif)
本环境使用 Laragon
集成 php-7.1.1
、nginx-1.10.1
、mariadb-10.2.3
、composer
、nodejs
。
[](https://lccdn.phphub.org/uploads/images/201703/28/5698/7RnQCeXbxA.png)
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/7RnQCeXbxA.png)
Laravel
项目laravel
laravel new favorites
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/rnC0ikk2Qe.png)
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/fovY58TzDm.png)
我们安装Laravel
的版本
[](https://lccdn.phphub.org/uploads/images/201703/28/5698/fhfPCu4we6.png)
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/fhfPCu4we6.png)
npm
模块[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/ZJMapDiwNJ.png)
创建文章和收藏表。-m
参数可以在创建模型的同时创建数据库迁移文件
php artisan make:model Post -m
php artisan make:model Favorite -m
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/ru82YlcRbo.png)
我们分别编辑两个数据库迁移文件
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->text('body');
$table->timestamps();
});
Schema::create('favorites', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->timestamps();
});
.env
文件链接数据库DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=favorite
DB_USERNAME=root
DB_PASSWORD=
create database favorite default charset utf8;
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/yvaMEQrIZd.png)
php artisan migrate
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/drnp8Cfwsa.png)
在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,
];
});
执行
php artisan make:seeder UsersTableSeeder
php artisan make:seeder PostsTableSeeder
编辑database/seeds/UsersTableSeeder.php
的run
方法
public function run()
{
factory(App\User::class, 5)->create();
}
编辑database/seeds/PostsTableSeeder.php
的run
方法
public function run()
{
factory(App\Post::class, 10)->create();
}
编辑database/seeds/PostsTableSeeder.php
的run
方法
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(PostsTableSeeder::class);
}
创建测试数据
php artisan db:seed
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/XI7lpERhdA.png)
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/VpuEVUzLpr.png)
一个用户可以收藏多个帖子,一个帖子可以被多个用户收藏。所以其关系为一对多对多。在User
模型中添加favorite
方法
修改User
的控制器
// 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();
}
php artisan auth
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/SU5S3dNQ42.png)
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/wrdqddTlyH.png)
Route::get('/', 'PostsController@index');
Route::post('favorite/{post}', 'PostsController@favoritePost');
Route::post('unfavorite/{post}', 'PostsController@unFavoritePost');
Route::get('my_favorites', 'UsersController@myFavorites')->middleware('auth');
php artisan make:controller PostsController
编辑PostsController
的index
方法
// 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); //分页每页5条
return view('posts.index', compact('posts'));
}
php artisan make:controller UsersController
编辑
<?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\layouts\add.blade.php
模板中的<title>
添加 <title>{{ config('app.name', 'Laravel') }}</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
logout
添加我的收藏夹<li>
<a href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
<li>
<a href="{{ url('my_favorites') }}">My Favorites</a>
</li>
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>
@if (Auth::check())
<div class="panel-footer">
<favorite
:post={{ $post->id }}
:favorited={{ $post->favorited() ? 'true' : 'false' }}
></favorite>
</div>
@endif
</div>
@empty
<p>No post created.</p>
@endforelse
{{ $posts->links() }}
</div>
</div>
</div>
@endsection
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
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
public function index()
{
$posts = Post::paginate(5);
return view('posts.index', compact('posts'));
}
/**
* 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();
}
}
<?php
namespace App;
use App\Favorite;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function favorited()
{
return (bool) Favorite::where('user_id', Auth::id())
->where('post_id', $this->id)
->first();
}
}
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>
Vue.component('favorite', require('./components/Favorite.vue'));
npm run dev
[
](https://lccdn.phphub.org/uploads/images/201703/28/5698/oexbX8GJ32.png)
最后在浏览器中访问,我们新建在Laragon
中的www
目录下的文件夹,Laragon
都会自动给我们创建了可以浏览的虚拟域名。直接访问
[](https://lccdn.phphub.org/uploads/images/201703/29/5698/zhloDjJo5G.gif)
[
](https://lccdn.phphub.org/uploads/images/201703/29/5698/zhloDjJo5G.gif)
Original url: Access
Created at: 2018-10-10 18:54:37
Category: default
Tags: none
未标明原创文章均为采集,版权归作者所有,转载无需和我联系,请注明原出处,南摩阿彌陀佛,知识,不只知道,要得到
最新评论