V
V
Vova1357982022-01-17 21:52:08
Laravel
Vova135798, 2022-01-17 21:52:08

Why does not all data reach the database?

When creating a post, tags are selected using checkboxes. If you select several flags, then only one will reach the database.
The tags and posts table is linked, maybe this is the problem.

<form method="POST" action="/addpost">
                <div class="form-group">
                    <p><input type="text" name="title"></p>
                    <p> <textarea name="content" cols="30" rows="10"></textarea> </p>
                    <p><select name="category">
                        @foreach($categories as $category)
                        <option value="{{ $category->title }}">{{ $category->title }}</option>
                        @endforeach
                    </select></p>
                    <p><h3>Tags</h3></p>
                        @foreach($tags as $tag)
                        <p><input type="checkbox" name="tags" value="{{ $tag->title }}">{{ $tag->title }}</p>
                        @endforeach
                    <button type="submit">Add post</button>
                </div>
                {{ csrf_field() }}
            </form>

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Post;
use App\Models\Tag;
use App\Models\category;

class PostController extends Controller
{
    public function all(){
        foreach(Post::all() as $post){
            echo $post->title;
        }
    }

    public function add(){
        $tags = Tag::all();
        $categories = Category::all();
        return view('addPost', compact('tags', 'categories'));
    }

    public function create(Request $request){
        $this->validate($request, [
            'title' => 'required',
        ]);
        $post = new Post();
        $post->title = $request->title;
        $post->category = $request->category;
        $post->content = $request->content;
        $post->tags = $request->tags;
        $post->creator = Auth::user()->name;
        $post->save();
        return redirect('/dashboard');
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question