Display data from multiple different tables in Laravel search

mekol :

I've been working on the search function for my library application, which is my first Laravel project so I am kinda struggling. I have finally figured out the search function, where I can search for a book by its title, however, I can't display any data from the search that is not in that table. If I run the search I get the following error message:

Facade\Ignition\Exceptions\ViewException
Undefined property: stdClass::$authors (View: /Users/krisz/code/project/resources/views/books/index.blade.php)

I have created a pivot table between 'books' and 'authors' and if I want to display the data only on my index page without searching it works, but after searching I cannot get it to work. Also, if I delete all the data from my index.blade.php which is outside the "books" table the search works correctly.

Could you please help me with this problem?

BookController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Book;
use App\Language;
use App\Genre;
use App\Author;
use App\Publisher;
use App\User;
use Illuminate\Support\Facades\DB;

class BookController extends Controller
{ 
    public function index(Request $request)
    {
        $books = Book::with('language')->get();
        $books = Book::with('user')->get();
        $languages = Language::all();
        $genres = Genre::all();
        $publishers = Publisher::all();
        $users = User::all();
        $authors = Author::all();

        return view('books/index', compact('books','languages','genres','publishers','users'));
    }

    public function search(Request $request)
    {
        $authors = Author::all();
        $books = Book::with('language')->get();
        $books = Book::with('user')->get();
        $languages = Language::all();
        $genres = Genre::all();
        $publishers = Publisher::all();
        $users = User::all();

        $search = $request->get('search');
        $books = DB::table('books')
            ->where('title','like','%' .$search. '%')
            ->paginate(5);
        return view('books/index')
             ->with(compact('books','languages','genres','authors','publishers','users'));
    }
}

index.blade.php:

@extends('layout')


@section('title')
<title>Alle Bücher</title>
@section('content')
<style>
  .uper {
    margin-top: 40px;
  }
</style>
<div class="uper">
  @if(session()->get('success'))
  <div class="alert alert-success">
    {{ session()->get('success') }}
  </div><br />
  @endif
  <div align="left">
            <div class="col-md-4">
                <h1>Policy</h1>


            </div>
            <div class="col-md-4">
                <form action="{{ route('search') }}" method="get" role="search">
                    {{ csrf_field() }}
                    <div class="input-group">
                        <input type="text" class="form-control" name="search" placeholder="Search Title" <span class="input-group-btn">
                            <button type="submit" class="btn btn-primary">Search</button></span>
                    </div>
                </form>
            </div>
        </div>
  <table class="table table-hover">
    <thead>
      <tr>
        <td>ID</td>
        <td>Titel</td>
        <td colspan="2">Autor</td>
        <td>Jahr</td>
        <td colspan="2">Verlag</td>
        <td colspan="2">Genre</td>
        <td>Sprache</td>
        <td>ISBN</td>
        <td>Seitenzahl</td>
        <td>Ausgeliehen von:</td>
        <td colspan="2">Funktionen</td>
      </tr>
    </thead>
    <tbody>
      @foreach($books as $book)
      <tr>
        <td>{{$book->id}}</td>
        <td>{{$book->title}}</td>
        @foreach($book->authors as $author)
        <td>{{$author->name}}</td>
        @endforeach
        <td>{{$book->year}}</td>
        @foreach($book->publishers as $publisher)
        <td>{{$publisher->name}}</td>
        @endforeach
        @foreach($book->genres as $genre)
        <td>{{$genre->name}}</td>
        @endforeach
        <td>{{$book->language->name}}</td>
        <td>{{$book->isbn}}</td>
        <td>{{$book->pages}}</td>
        <td>{{$book->user->name}}</td>

        <td><a href="{{ route('books.edit', $book->id)}}" class="btn btn-primary">Bearbeiten</a></td>
        <td>
          <form action="{{ route('books.destroy', $book->id)}}" method="post">
            @csrf
            @method('DELETE')
            <button class="btn btn-danger" type="submit">Löschen</button>
          </form>
        </td>
      </tr>
      @endforeach
    </tbody>
  </table>
  <div>
    @endsection

Book Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

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 user(){
    return $this->belongsTo(User::class);
}

}
miken32 :

First, you're just overwriting yourself here:

$books = Book::with('language')->get();
$books = Book::with('user')->get();

I suspect you want both language and user, and you probably want the authors, as well as some other data you try to fetch in the view? This is called eager loading and it's done on multiple relationships like this:

$books = Book::with(['language', 'user', 'authors', 'publishers', 'genres'])->get();

Not sure about the error you're getting, as $book should be an instance of App\Book and not stdClass, and relations should still be available even if not eager loaded. I suspect there's some code you're not showing or your models are not defined correctly.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=24934&siteId=1