kriszpchicken's avatar

Values won't be sent to databank

I have created a form, where I can add a new book. However, after I push the create button nothing happens, it just refreshes. Could you please help me with this problem?

Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;
use App\Language;
use App\Genre;
use App\Author;
use App\Publisher;

class BookController extends Controller
{ 
    public function index(Request $request)
    {
        $books = Book::with(['language', 'authors', 'publishers', 'genres'])->get();

        return view('books/index', compact('books'));
    }

    public function create()
    {
        $languages = Language::all();
        $genres = Genre::all();
        $authors = Author::all();
        $publishers = Publisher::all();
        
        return view('books/create', compact('languages','genres','authors','publishers'));
    }
     
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'authors' => 'array|min:1',
	        'authors.*' => 'exists:authors,id',
            'year' => 'required|numeric|max:2500',
            'publishers' => 'array|min:1',
	        'publishers.*' => 'exists:publishers,id',
            'genres' => 'array|min:1',
            'genres.*' => 'exists:genres,id',
            'language_id' => 'required',
            'isbn' => 'required|numeric|max:9999999999999',
            'pages' => 'required|numeric',
        ]);

        $book = Book::create($validatedData);
        $book->authors()->attach(request('authors'));
        $book->genres()->attach(request('genres'));
        $book->publishers()->attach(request('publishers'));


        return redirect('books')->with('success', 'Buch wurde erfolgreich hinzugefügt!');
    }

    public function show($id)
    {
        $book = Book::findOrFail($id);
        $languages = Language::all();
        $genres = Genre::all();
        $authors = Author::all();
        $publishers = Publisher::all();


        return view('books/show', compact('book', 'languages', 'genres','authors','publishers'));
    }

    public function edit($id)
    {
        $book = Book::findOrFail($id);
        $languages = Language::all();
        $genres = Genre::all();
        $authors = Author::all();
        $publishers = Publisher::all();

        return view('books/edit', compact('book', 'languages', 'genres','authors','publishers'));
    }

    public function update(Request $request, $id)
    {
        $book=Book::findorFail($id);
        $validatedData = $request->validate([
            'title' => 'required|max:255',
            'authors' => 'exists:authors,id',
            'year' => 'required|numeric|max:2500',
            'publishers' => 'exists:publishers,id',
            'genres' => 'exists:genres,id',
            'language_id' => 'required',
            'isbn' => 'required|numeric|max:9999999999999',
            'pages' => 'required|numeric',
        ]);
        $validatedData =$request->all();
        $book->fill($validatedData)->save();
        $book->authors()->attach(request('authors'));
        $book->genres()->attach(request('genres'));
        $book->publishers()->attach(request('publishers'));

        return redirect('books')->with('success', 'Buch wurde erfolgreich bearbeitet!');
    }

    public function destroy($id)
    {
        $book = Book::findOrFail($id);
        $book->delete();

        return redirect('books')->with('success', 'Buch wurde erfolgreich entfernt!');
    }

    public function search(Request $request)
{
    $validatedData =$request->validate([
        'book_search' => 'min:3',
    ]);

    $search = $request->get('book_search');
    $books = Book::with(['language', 'authors', 'publishers', 'genres'])->where('title','like','%' .$search. '%')->get();
    
    return view('books/index', compact('books'));
    
}
}

create.blade.php

@extends('layout')


@section('title')
<title>Neues Buch hinzufügen</title>
@section('stylesheets')
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />


@endsection
@section('content')
<style>
    .uper {
        margin-top: 40px;
    }
</style>
<div class="card uper">
    <div class="card-header">
        Neues Buch hinzufügen
    </div>
    <div class="card-body">
        <form method="post" action="{{ route('books.store') }}">
            
        <div class="form-group">
                @csrf
                <label for="title">Titel:</label>
                <input type="text" class="form-control" name="title" value="{{ old('title')}}" />
                @error('title')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="authors">Author(en):</label>
                <select name="authors[]" multiple class="form-control select2-multi <!-- @error('authors') is-invalid @enderror -->">
                    @foreach ($authors as $author)
                    <option value="{{ $author->id }}" {{ in_array($author->id, old('authors') ?? []) ? 'selected' : '' }}>
                        {{ $author->name }}
                    </option>
                    @endforeach
                </select>
                @error('authors')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="year">Jahr:</label>
                <input type="text" class="form-control" name="year" value="{{ old('year')}}" />
                @error('year')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="publishers">Verlag(e):</label>
                <select name="publishers[]" multiple class="form-control select2-multi <!-- @error('publishers') is-invalid @enderror -->">
                    @foreach ($publishers as $publisher)
                    <option value="{{ $publisher->id }}" {{ in_array($publisher->id, old('publishers') ?? []) ? 'selected' : '' }}>
                        {{ $publisher->name }}
                    </option>
                    @endforeach
                </select>
                @error('publishers')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="genres">Genre(s):
                @foreach($genres as $genre)
                <input type="checkbox" name="genres[{{$genre->id}}]"@if(array_key_exists($genre->id, old('genres', []))) checked @endif > {{$genre->name}}
                @endforeach
            </label>
                </select>
                @error('genre_id')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="language_id">Sprache:</label>
                <select name="language_id" class="form-control @error('language_id') is-invalid @enderror">
                    <option value="{{ old('language_id')}}">-- {{ __('Spache auswählen') }} --</option>
                    @foreach ($languages as $language)
                    @if (old('language_id') == $language->id)
                    <option value="{{ $language->id }}" selected>{{ $language->name }}</option>
                    @else
                    <option value="{{ $language->id }}">{{ $language->name }}</option>
                    @endif
                    @endforeach
                </select>
                @error('language_id')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="isbn">ISBN:</label>
                <input type="text" class="form-control" name="isbn" value="{{ old('isbn')}}" />
                @error('isbn')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="form-group">
                <label for="pages">Seitenzahl:</label>
                <input type="text" class="form-control" name="pages" value="{{ old('pages')}}" />
                @error('pages')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <button type="submit" class="btn btn-primary">Hinzufügen</button>
        </form>
    </div>
</div>
<script type="text/javascript">
        $(".select2-multi").select2();
	</script>

@endsection

Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    protected $fillable = ['title', 'year', 'language_id', 'isbn', 'pages', 'authors','publisher','genres'];

public function publishers(){
     return $this->belongsToMany(Publisher::class);
}

public function authors(){
   return $this->belongsToMany(Author::class);
} 

public function genres(){
     return $this->belongsToMany(Genre::class);
}

public function language(){
    return $this->belongsTo(Language::class);
}

public function readers()
    {
        return $this
            ->belongsToMany(Reader::class, 'book_reader')
            ->using(Checkout::class)
            ->withPivot(['id', 'returndate', 'maxreturndate']);
    }


}

0 likes
13 replies
Sti3bas's avatar

@mekol make sure you don't have any validation errors, you can test that by adding this to your template and then submitting the form:

@foreach($errors->all() as $error)
   <div>{{ $error }}</div>
@endforeach
deansatch's avatar

Looks like your genre_id error is set up wrong so probably just outputs no message - do as Sti3bas says and hopefully you get more info on that

kriszpchicken's avatar

I only get these error messages: The title field is required. The year field is required. The language id field is required. The isbn field is required. The pages field is required.

So basically I can't get any for the fields that I have connected through ManytoMany relationships. Could you maybe help me with how I should change my Controller?

Snapey's avatar

have you set them as $fillable since you are doing mass assignment?

kriszpchicken's avatar

I have updated my question with my Model. Now I get the error message The selected genres.3 is invalid.

Snapey's avatar

did you fix the fillable issue, and now its a different problem?

kriszpchicken's avatar

Yes, it used to work though before without inserting publishers, authors and genres into the fillable because those are not in the table books. They are different tables which I have joined with my books table.

Snapey's avatar

anyway,

your genres checkboxes don't have a value so will return 'on'. This is not a valid value in your genres table.

What can I help you with next?

kriszpchicken's avatar

Thank you! Could you tell me how I can fix that? I'm kind of lost as you can see

Snapey's avatar
Snapey
Best Answer
Level 122

you could set the value to the id I think?

kriszpchicken's avatar

Oh wow, yes that totally makes sense, sorry I blacked out on this for a minute.

It work correctly now, thank you so much! However, I can't get the error messages to work at genres, publishers and authors...

Do you have any idea what I could do?

Snapey's avatar

probably put the @error inside the foreach loop and use

            @error('genre.'. $genre->id)
            <div class="alert alert-danger">{{ $message }}</div>
            @enderror

or put it outside the for each loop, then iterate over each of the genre errors

kriszpchicken's avatar

I can submit the form without inputting anything into genres, publisher and authors, so probably the validation is false, but I don't know what could be false about it.

Please or to participate in this conversation.