Chào mừng!

Bằng cách đăng ký với chúng tôi, bạn sẽ có thể thảo luận, chia sẻ và nhắn tin riêng tư với các thành viên khác trong cộng đồng của chúng tôi.

Đăng ký ngay!
  • Chào Khách,
    Bạn cần liên hệ với admin ??? ZALO & TELEGRAM

Cần giúp laravel

Tham gia
15/12/23
Bài viết
6
Lượt Thích
0
Coins
520
em đang làm 1 đồ án nhỏ mạng xã hội sử dụng chính là laravel hiện tại eđang làm tính năng thêm hashtag và dropdown dữ liệu hasgtag từ database về,
em mắc 1 số lỗi sau: không lấyđược dữ liệu từ form sau khi submit


HTML:
<div class="wrapper">
    <div class="content my-3">
        <ul id="tagList" class="flex flex-wrap ">
            <input type="text" placeholder="Add up to tags..." spellcheck="false" name="hashtag" class="outline-none p-2"
                id="tagInput" />
        </ul>
    </div>
</div>
JavaScript:
<script>
    const tagList = document.getElementById("tagList"),
        tagInput = document.getElementById("tagInput");
    let maxTags = 4,
        tags = [];
    countTags();
    createTag();
    function countTags() {
        tagInput.focus();
        // Kiểm tra số lượng tags để ẩn hiện ô input
        if (tags.length >= maxTags) {
            tagInput.classList.add("hidden");
        } else {
            tagInput.classList.remove("hidden");
        }
    }
    function createTag() {
    tagList.querySelectorAll("li").forEach((li) => li.remove());
    tags.slice().reverse().forEach((tag) => {
        let liTag = `<li class="rounded-sm border border-gray-100 mr-2 p-2" name="hashtag">
                        <div class="">
                            <button type="button" name="hashtag" onclick="getTagValue(this)">
                                <span>#</span> ${tag} 
                            </button>
                            <button type="button" onclick="removeTag('${tag}')" class="cursor-pointer">
                                <i class="uit uit-multiply rounded-full w-5 h-5"></i>
                            </button>
                        </div>
                    </li>`;
        tagList.insertAdjacentHTML("afterbegin", liTag);
    });
    countTags();
    getButtonValues(); // Gọi hàm để lấy giá trị của các thẻ <button>
}
    function getButtonValues() {
    // Lấy giá trị của 4 thẻ <button>
    let buttonValues = Array.from(document.querySelectorAll("ul#tagList li button[name='hashtag']"))
        .slice(0, 4)
        .map((button) => button.innerText.trim());
    
    
    
}
    function removeTag(tag) {
        let index = tags.indexOf(tag);
        tags = [...tags.slice(0, index), ...tags.slice(index + 1)];
        createTag();
    }
    function addTag(e) {
    if (e.key === "Enter") {
        e.preventDefault();
        let tag = e.target.value.replace(/\s+/g, " ");
        if (tag.length > 1) {
            let existingIndex = tags.indexOf(tag);
            if (existingIndex !== -1) {
                tags.splice(existingIndex, 1);
            } else if (tags.length < maxTags) {
                tag.split(",").forEach((tag) => {
                    tag = tag.trim(); // Loại bỏ khoảng trắng ở đầu và cuối tag
                    tags.push(tag);
                    createTag();
                    getButtonValues(); // Gọi hàm để lấy giá trị của các thẻ <button>
                });
            }
        }
        e.target.value = "";
    }
}
    tagInput.addEventListener("keydown", addTag);
</script>
PHP:
 public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            // Tạo 1 bài viết mới
            $dataPost = new Diary;
            $dataPost->title = $request->title;
            $dataPost->content = HTMLPurifier::clean($request->content);
            $dataPost->status = $request->status;
            $dataPost->user_id = Auth::id();
          
            // XỬ lý ảnh
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('postDiary', 'public');
                $dataPost->image = $imagePath;
            }
            
            // Lưu bài viết
            $dataPost->save();
               // Xử lý HashTag
               $hashTag = explode('#', $request->hashtag);
               array_shift($hashTag);
               foreach ($hashTag as $tag) {
                   $tag = trim(strtolower($tag));
                   $hashtag_id = Hashtag::where('content', $tag)->value('id');
                   if (!$hashtag_id) {
                       // Hashtag chưa tồn tại, thêm mới
                       $newHashTag = Hashtag::create(['content' => $tag]);
                       $hashtag_id = $newHashTag->id;
                   }
                   // Liên kết Hashtag với Post trong bảng trung gian
                   $dataPost->hashtags()->attach($hashtag_id);
               }
            // Commit Tranction nếu mọi thứ thành công
            DB::commit();
            Log::info('Đăng bài viết thành công', ['user_id' => Auth::id(), 'post_id' => $dataPost->id]);
            return redirect('/user/create')->with('msgSuccess', 'Đăng bài viết thành công');
            // dd('Success');
        } catch (\Exception) {
            // RollBack transaction nếu có lỗi
            DB::rollBack();
            Log::error('Đăng bài viết thất bại', ['user_id' => Auth::id()]);
            return redirect('/user/create')->with('msgFail', 'Đăng bài viết thất bại');
            // dd('Fail');
        }
    }
 
Tham gia
2/4/24
Bài viết
93
Lượt Thích
0
Coins
1,150
em đang làm 1 đồ án nhỏ mạng xã hội sử dụng chính là laravel hiện tại eđang làm tính năng thêm hashtag và dropdown dữ liệu hasgtag từ database về,
em mắc 1 số lỗi sau: không lấyđược dữ liệu từ form sau khi submit


HTML:
<div class="wrapper">
    <div class="content my-3">
        <ul id="tagList" class="flex flex-wrap ">
            <input type="text" placeholder="Add up to tags..." spellcheck="false" name="hashtag" class="outline-none p-2"
                id="tagInput" />
        </ul>
    </div>
</div>
JavaScript:
<script>
    const tagList = document.getElementById("tagList"),
        tagInput = document.getElementById("tagInput");
    let maxTags = 4,
        tags = [];
    countTags();
    createTag();
    function countTags() {
        tagInput.focus();
        // Kiểm tra số lượng tags để ẩn hiện ô input
        if (tags.length >= maxTags) {
            tagInput.classList.add("hidden");
        } else {
            tagInput.classList.remove("hidden");
        }
    }
    function createTag() {
    tagList.querySelectorAll("li").forEach((li) => li.remove());
    tags.slice().reverse().forEach((tag) => {
        let liTag = `<li class="rounded-sm border border-gray-100 mr-2 p-2" name="hashtag">
                        <div class="">
                            <button type="button" name="hashtag" onclick="getTagValue(this)">
                                <span>#</span> ${tag}
                            </button>
                            <button type="button" onclick="removeTag('${tag}')" class="cursor-pointer">
                                <i class="uit uit-multiply rounded-full w-5 h-5"></i>
                            </button>
                        </div>
                    </li>`;
        tagList.insertAdjacentHTML("afterbegin", liTag);
    });
    countTags();
    getButtonValues(); // Gọi hàm để lấy giá trị của các thẻ <button>
}
    function getButtonValues() {
    // Lấy giá trị của 4 thẻ <button>
    let buttonValues = Array.from(document.querySelectorAll("ul#tagList li button[name='hashtag']"))
        .slice(0, 4)
        .map((button) => button.innerText.trim());
   
   
   
}
    function removeTag(tag) {
        let index = tags.indexOf(tag);
        tags = [...tags.slice(0, index), ...tags.slice(index + 1)];
        createTag();
    }
    function addTag(e) {
    if (e.key === "Enter") {
        e.preventDefault();
        let tag = e.target.value.replace(/\s+/g, " ");
        if (tag.length > 1) {
            let existingIndex = tags.indexOf(tag);
            if (existingIndex !== -1) {
                tags.splice(existingIndex, 1);
            } else if (tags.length < maxTags) {
                tag.split(",").forEach((tag) => {
                    tag = tag.trim(); // Loại bỏ khoảng trắng ở đầu và cuối tag
                    tags.push(tag);
                    createTag();
                    getButtonValues(); // Gọi hàm để lấy giá trị của các thẻ <button>
                });
            }
        }
        e.target.value = "";
    }
}
    tagInput.addEventListener("keydown", addTag);
</script>
PHP:
public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            // Tạo 1 bài viết mới
            $dataPost = new Diary;
            $dataPost->title = $request->title;
            $dataPost->content = HTMLPurifier::clean($request->content);
            $dataPost->status = $request->status;
            $dataPost->user_id = Auth::id();
         
            // XỬ lý ảnh
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('postDiary', 'public');
                $dataPost->image = $imagePath;
            }
           
            // Lưu bài viết
            $dataPost->save();
               // Xử lý HashTag
               $hashTag = explode('#', $request->hashtag);
               array_shift($hashTag);
               foreach ($hashTag as $tag) {
                   $tag = trim(strtolower($tag));
                   $hashtag_id = Hashtag::where('content', $tag)->value('id');
                   if (!$hashtag_id) {
                       // Hashtag chưa tồn tại, thêm mới
                       $newHashTag = Hashtag::create(['content' => $tag]);
                       $hashtag_id = $newHashTag->id;
                   }
                   // Liên kết Hashtag với Post trong bảng trung gian
                   $dataPost->hashtags()->attach($hashtag_id);
               }
            // Commit Tranction nếu mọi thứ thành công
            DB::commit();
            Log::info('Đăng bài viết thành công', ['user_id' => Auth::id(), 'post_id' => $dataPost->id]);
            return redirect('/user/create')->with('msgSuccess', 'Đăng bài viết thành công');
            // dd('Success');
        } catch (\Exception) {
            // RollBack transaction nếu có lỗi
            DB::rollBack();
            Log::error('Đăng bài viết thất bại', ['user_id' => Auth::id()]);
            return redirect('/user/create')->with('msgFail', 'Đăng bài viết thất bại');
            // dd('Fail');
        }
    }
Trong HTML form của bạn, bạn không có một phần tử để gửi dữ liệu hashtag lên server. Bạn cần thêm một phần tử input hoặc textarea để người dùng nhập hashtag và gửi dữ liệu lên server. vd
<form action="{{ route('store') }}" method="POST">
@csrf
<input type="text" placeholder="Add hashtags..." name="hashtag" id="hashtagInput" />
<!-- Các phần tử HTML khác -->
<button type="submit">Submit</button>
</form>

- Trong JavaScript, hàm addTag(e) không được gọi khi bạn nhấn nút "Enter" trên input. Bạn cần sửa đổi hàm addTag(e) để nó được gọi khi sự kiện keydown xảy ra trên input. Bên cạnh đó, bạn cũng cần đảm bảo rằng các giá trị hashtag được gửi đến server thông qua form
function addTag(e) {
if (e.key === "Enter") {
e.preventDefault();
let tag = tagInput.value.trim();
if (tag.length > 0) {
tags.push(tag);
createTag();
tagInput.value = ""; // Xóa giá trị trong input
countTags(); // Cập nhật hiển thị số lượng tags
}
}
}

-Trong controller của bạn, bạn cần sử dụng key "hashtag" để truy xuất giá trị được gửi từ form.
public function store(Request $request)
{
// Các xử lý khác...
// Lấy giá trị hashtag từ request
$hashTag = $request->hashtag;
// Xử lý và lưu các hashtag vào cơ sở dữ liệu
// Các xử lý khác...
}
Bạn có thể tham khải mong nó sẽ giúp ích cho bạn phần nào

-----
CÔNG TY TNHH CÔNG NGHỆ ZLINK VIỆT NAM
Cung cấp license phần mềm, Giải pháp hạ tầng mạng, tổng đài thoại, contact center, CRM
zlink.vn / azsoft.com / voip.com.vn
email: [email protected] ; [email protected]
 
Top Bottom
AdBlock Detected

We get it, advertisements are annoying!

Sure, ad-blocking software does a great job at blocking ads, but it also blocks useful features of our website. For the best site experience please disable your AdBlocker.

I've Disabled AdBlock
No Thanks