02:实现收藏流程
@extends('app')
@section('content')
{--chunk(3)这里实现的是每一行显示三个,就是把一个大数据分整3个一组的大二维数组--}
@foreach( $lessons->chunk(3) as $row )
<div class="row">
@foreach( $row as $lesson )
<article class="col-md-4">
<h2>
{ $lesson->title }
</h2>
<img src="{$lesson->image}" width="360" alt="">
<div class="body">
<form action="/favorite" method="post">
{ csrf_token() }
<input type="hidden" name="lesson_id" value="{ $lesson->id }">
<button type="submit" class="btn btn-primary">收藏</button>
</form>
{--下面增加--}
{ $lesson->intro }
</div>
</article>
@endforeach
</div>
@endforeach
{!! $lessons->appends( ['type'=>'article'] )->render() !!}
@stop
php artisan make:controller FavoritesController
Route::resource( '/favorite','FavoritesController' );
public function store(Request $request)
{
Auth::user()->favorites()->attach( $request->get( 'lesson_id' ) );
return redirect()->back();
}
<form action="/favorite" method="post">
{ csrf_field() }
<input type="hidden" name="lesson_id" value="{ $lesson->id }">
<button type="submit" class="btn { in_array( $lesson->id,$favorites ) ? 'btn-success' : 'btn-primary' }">收藏</button>
</form>
$favorites = \App\Favorite::where( 'user_id',Auth::user()->id )
->lists('lesson_id')->ToArray();
return view( 'lessons.index',compact('lessons','favorites'));
@extends('app')
@section('content')
@foreach( $lessons->chunk(3) as $row )
<div class="row">
@foreach( $row as $lesson )
<article class="col-md-4">
<h2>
{ $lesson->title }
</h2>
<img src="{$lesson->image}" width="360" alt="">
<div class="body">
@if( in_array( $lesson->id,$favorites ) )
<form action="/favorite/{$lesson->id}" method="POST">
<input type="hidden" name="_method" value="DELETE">
@else
<form action="/favorite" method="post">
@endif
{ csrf_field() }
<input type="hidden" name="lesson_id" value="{ $lesson->id }">
<button type="submit" class="{ in_array( $lesson->id,$favorites ) ? 'btn btn-success' : 'btn btn-primary' }">收藏</button>
</form>
{ $lesson->intro }
</div>
</article>
@endforeach
</div>
@endforeach
{!! $lessons->render() !!}
@stop
public function destroy($id)
{
\Auth::user()->favorites()->detach( $id );
return redirect()->back();
}
public function index()
{
\Auth::user()->favorites();
}
最后测试收藏与取消收藏
按钮颜色变换:成功
数据库增减数据:成功
PS:嗯,整体效果跟视频一样