sweetalert2 收藏功能代码备份

file

file

import Swal from 'sweetalert2'

按钮

<span role="button" class="link-primary" data-collection-add='{"cid":"123", "type":"Topic"}'>收藏</span>

js(jq)

<script>
$(document).on("click", "[data-collection-add]",function (e) {
    var cid = $(this).data('collection-add').cid;
    var ctype = $(this).data('collection-add').type;
    e.preventDefault();
    Swal.fire({
        title: '<span class="fs-4 fw-normal">收藏</span>',
        html: '<p class="mt-3 font-14 text-black-50">请选择你想添加的收藏夹,或<a href="javascript:;" class="ms-2" data-collection-create="">创建收藏夹</a></p><div id="add-form-box" class="p-4" style="max-height: 300px;overflow-y: auto;"></div>',
        showCancelButton: true,
        confirmButtonText: '收藏',
        cancelButtonText: '取消',
        backdrop : true,
        customClass: {
            confirmButton: 'btn btn-primary px-4',
            cancelButton: 'btn btn-outline-danger px-4 ms-3'
        },
        onOpen: function () {
            var cfel = '';
            $.ajax({
                type: "GET",
                url: "/collection/my",
                cache: false,
                data: {type:ctype, cid:cid},
                dataType: "json",
                beforeSend: function() {
                    $('#add-form-box').html('<div class="spinner-border text-primary" role="status"></div>');
                },
                success:function(data){
                    switch(data.code){
                        case 200:
                            cfel += '<form id="collection-add-form" method="POST"><input type="hidden" name="cid" value="'+cid+'"><input type="hidden" name="type" value="'+ctype+'">';
                            $.each(data.data, function (index, value){
                                var checked = value.checked ? 'checked' : '';
                                cfel += '<div class="d-flex align-items-center mb-3 font-15"><div class="text-start me-auto"><input type="checkbox" id="collection-'+value.id+'" name="collection_id[]" value="'+value.id+'" class="form-checkbox me-2" '+checked+'><label class="font-15" for="collection-'+value.id+'">'+value.name+'</label></div><span class="badge rounded-pill badge-soft-primary fw-normal px-2">'+value.contents_count+'</span></div>'
                            });
                            cfel += '</form>';
                            $('#add-form-box').html(cfel);
                        break;
                        case 0:
                            $('#add-form-box').html('<div class="">暂无收藏夹</div>');
                        break;
                    }
                }
            });
        },
        buttonsStyling: false
    }).then(function(result) {
        if (result.value) {
            var data = $("#collection-add-form").serialize();
            $.ajax({
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                type: "POST",
                url: "/collection/add",
                cache: false,
                data: data,
                dataType: "json",
                success:function(res){
                    switch(res.code){
                        case 200:
                            Swal.fire({
                                type: 'success',
                                title: '<span class="fs-4 fw-normal">收藏成功</span>',
                                showConfirmButton: false,
                            });
                            $('[data-collection-add]').text('已收藏');
                        break;
                        case 0:
                            Swal.fire({
                                type: 'info',
                                title: '<span class="fs-4 fw-normal">'+res.msg+'</span>',
                                showConfirmButton: false,
                            });
                            $('[data-collection-add]').text('收藏');
                        break;
                    }
                },
                error: function (res) {
                    errors = res.responseJSON.errors;
                    $.each(errors, function(i) {
                       Swal.fire({
                            icon: 'error',
                            type: 'error',
                            title: '<span class="fs-4 fw-normal">收藏失败!</span>',
                            html: '<p class="alert alert-danger mx-4 font-14 mt-4 py-2">'+errors[i][0]+'</p>',
                            showConfirmButton: false,
                        });
                    });
                }
            });
        }
    });
});
$(document).on("click", "[data-collection-create]",function (e) {
    e.preventDefault();
    Swal.fire({
        title: '<span class="fs-4 fw-normal">新收藏夹</span>',
        html: '<p class="mt-3 font-14 text-black-50">创建新的收藏夹,或<a href="javascript:;" class="ms-2" data-collection-back>选择已有收藏夹</a></p><div class="p-4 text-start font-15"><form id="collection-create-form" method="POST"><div class="mb-3"><label class="form-label" for="name">名称</label><input type="text" id="name" name="name" class="form-control"></div><div class="mb-3"><label class="form-label" for="description">描述</label><textarea id="description" name="description" class="form-control"></textarea></div><div class="form-check form-switch form-switch-success d-flex align-items-center"><input class="form-check-input mt-0 me-2" type="checkbox" id="customSwitchSuccess" name="open" checked=""><label class="form-check-label" for="customSwitchSuccess">公开的</label></div></form></div>',
        showCancelButton: true,
        confirmButtonText: '创建',
        cancelButtonText: '取消',
        backdrop : true,
        customClass: {
            confirmButton: 'btn btn-primary px-4',
            cancelButton: 'btn btn-outline-danger px-4 ms-3'
        },
        buttonsStyling: false,
    }).then(function(result) {
        if (result.value) {
            var data = $("#collection-create-form").serialize();
            $.ajax({
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                type: "POST",
                url: "/collection/create",
                cache: false,
                data: data,
                dataType: "json",
                success:function(res){
                    if(res.code == 200){
                        $('[data-collection-add]').click();
                    }
                },
                error: function (res) {
                    errors = res.responseJSON.errors;
                    $.each(errors, function(i) {
                       Swal.fire({
                            icon: 'error',
                            type: 'error',
                            title: '<span class="fs-4 fw-normal">创建失败!</span>',
                            html: '<p class="alert alert-danger mx-4 font-14 mt-4 py-2">'+errors[i][0]+'</p>',
                            showConfirmButton: false,
                        });
                    });
                }
            });
        }
    });
});
$(document).on("click", "[data-collection-back]",function (e) {
    $('[data-collection-add]').click();
});
</script>

路由

Route::prefix('collection')->group(function () {
    Route::match(['get', 'post'], 'create', [App\Http\Controllers\CollectionController::class, 'create'])->name('collection.create');
    Route::get('my', [App\Http\Controllers\CollectionController::class, 'my'])->name('collection.my');
    Route::post('add', [App\Http\Controllers\CollectionController::class, 'add'])->name('collection.add');
    Route::match(['get', 'post'], '{collection}/edit', [App\Http\Controllers\CollectionController::class, 'edit'])->name('collection.edit');
    Route::post('{collection}/delete', [App\Http\Controllers\CollectionController::class, 'delete'])->name('collection.delete');
    Route::get('{id}', [App\Http\Controllers\CollectionController::class, 'show'])->name('collection.show');
    Route::get('{id}/{cid}', [App\Http\Controllers\CollectionController::class, 'detail'])->name('collection.detail');
});

控制器CollectionController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use App\Models\Collection;
use App\Models\CollectionContent;
use App\Models\Topic;

class CollectionController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index']]);
        $this->middleware('verified', ['only' => ['add']]);
    }
    
    public function index()
    {
        //
    }
    
    public function my()
    {
        $type = @$_GET['type'] ?? '';
        $cid =  @$_GET['cid'] ?? '';
        $datas = Collection::where(['user_id'=>Auth::user()->id])->withCount('contents')->orderbydesc('id')->get();
        foreach($datas as $data){
            switch($type){
                case 'Topic':
                    $isCollection = CollectionContent::where(['collection_id'=>$data->id, 'cid'=>$cid])->first();
                break;
            }
            $data->checked = $isCollection ? true : false;
        }
        if(count($datas))return ['code'=>200, 'data'=>$datas];
        return ['code'=>0, 'data'=>$datas];
    }
    
    public function add(Request $request, CollectionContent $content)
    {
        $request->validate([
            'cid' => 'required',
            'type' => 'required|in:Topic',
        ],[
            'collection_id.*' => __('至少选择一个收藏夹吧'),
            'cid.*' => __('无法获取收藏的内容'),
            'type.*' => __('收藏类型不存在'),
        ]);
        switch($request->type){
            case 'Topic':
                $data = Topic::find($request->cid)->first();
            break;
        }
        if(!$data)return ['code' => 404, 'msg'=>'无法获取收藏的内容'];
        
        $mycontent = $content->where(['user_id'=>Auth::user()->id, 'cid'=>$request->cid]);
        $mycontent->delete();
        if($request->collection_id && count($request->collection_id) > 0){
            foreach($request->collection_id as $v){
                $content->create([
                    'collection_id' => $v,
                    'cid' => $request->cid,
                    'type' => $request->type,
                    'user_id' => Auth::user()->id,
                    'datas' => $data,
                ]);
            }
        }
        if(!$mycontent->first()){
            return ['code' => 0, 'msg'=>'没有收藏'];
        }
        return ['code' => 200];
    }

    public function create(Request $request, Collection $collection)
    {
        $request->validate([
            'name' => 'required|min:2|max:20',
            'description' => 'max:512',
            'open' => 'required|in:on,off',
        ],[
            'name.*' => __('名称2-20字'),
            'description.*' => __('描述最多512字'),
            'open.*' => __('开放类型错误'),
        ]);
        $collection->alias = Auth::user()->id.mt_rand(10000, 99999);
        $collection->name = $request->name;
        $collection->description = $request->description;
        $collection->open = $request->open;
        $collection->user_id = Auth::user()->id;
        $collection->save();
        return ['code' => 200];
    }

    public function show(Collection $collection)
    {
        return view('collection.show', compact('collection'));
    }

    public function edit(Collection $collection)
    {
        //
    }
    
    public function detail(Collection $collection)
    {
        return view('collection.detail', compact('collection'));
    }

    public function destroy(Collection $collection)
    {
        //
    }
}

模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class Collection extends Model
{
    public function contents(){
        return $this->hasMany(CollectionContent::class, 'collection_id', 'id');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CollectionContent extends Model
{
    protected $fillable = ['collection_id', 'cid', 'type', 'user_id', 'datas'];
}

数据表,创建

CREATE TABLE `pre_collections` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `alias` varchar(32) DEFAULT NULL,
 `name` varchar(32) DEFAULT NULL,
 `description` varchar(512) DEFAULT NULL,
 `user_id` int(11) DEFAULT NULL,
 `open` varchar(3) DEFAULT 'on',
 `total` int(11) DEFAULT '0',
 `created_at` timestamp NULL DEFAULT NULL,
 `updated_at` timestamp NULL DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `id` (`id`),
 KEY `id_2` (`id`),
 KEY `alias` (`alias`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
CREATE TABLE `pre_collection_contents` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `type` varchar(20) DEFAULT NULL,
 `collection_id` int(11) DEFAULT NULL,
 `cid` int(11) DEFAULT NULL,
 `user_id` int(11) DEFAULT NULL,
 `datas` text,
 `created_at` timestamp NULL DEFAULT NULL,
 `updated_at` timestamp NULL DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `id` (`id`),
 KEY `id_2` (`id`),
 KEY `cid` (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8