I am an Laravel beginnner and try now to build an Simple Searchbar on my site.
But I get this error:
Class 'products' not found
Can someone tell me please what I have forget in my Controllers?
Search form on Index:
<ul class="searchbar">
<form action="/search" class="light" method="POST" role="search">
{{ csrf_field() }}
<input type="text" class="form-control" name="q" placeholder="Find your item" />
<input type="submit" value="Search" />
</form>
search.blade.php:
#extends('master.main')
#if(Auth::check())
#section('main-content')
#component('master.notification')
#slot('size')
col-md-8 col-md-offset-2
#endslot
#slot('title')
Product Search
#endslot
<div class="container">
#if(isset($products))
<h2>Product Search</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach($products as $dummy)
<tr>
<td>{{$dummy->name}}</td>
<td>{{$dummy->description}}</td>
</tr>
#endforeach
</tbody>
</table>
{!! $products->render() !!}#endif
</div>
<div class="container">
#if(isset($details))
<p> The Search results for <b> {{ $query }} </b> are :</p>
<h2>Product Search</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach($details as $products)
<tr>
<td>{{$products->name}}</td>
<td>{{$products->description}}</td>
</tr>
#endforeach
</tbody>
</table>
#if($details){!! $details->render() !!}#endif
#elseif(isset($message))
<p>{{ $message }}</p>
#endif
</div>
#endcomponent
#stop
#endif
web.php:
Route::get ( '/', function () {
$mydatabase = products::paginate(25);
return view ( 'search' )->withproducts($mydatabase);
} );
Route::any ( '/search', function () {
$q = Input::get ( 'q' );
if($q != ""){
$products = products::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'description', 'LIKE', '%' . $q . '%' )->paginate (5)->setPath ( '' );
$pagination = $products->appends ( array (
'q' => Input::get ( 'q' )
) );
if (count ( $products ) > 0)
return view ( 'search' )->withDetails ( $products )->withQuery ( $q );
}
return view ( 'search' )->withMessage ( 'No Products found. Try to search again !' );
} );
The error comes from:
Route::get ( '/', function () {
$mydatabase = products::paginate(25);
How is products or Product::paginate defined or must I use in web.php the ProductController#...? Yes, I have found out its not my database table products ;) I think Product instead of products are correct, right?
/App/Product.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Storage;
class Product extends Model
{
public function category(){
return $this->belongsTo('App\Category');
}
public function seller(){
return $this->belongsTo('App\User');
}
public function buyer(){
return $this->belongsTo('App\User');
}
public function bids(){
return $this->hasMany('App\Bid');
}
public function purchases(){
return $this->hasMany('App\Purchase');
}
}
you must add (import your class products) in the begin of your controller (web.php for your case)
use namespace\products
replace namespace by your namespace(the path of the class products) exemple: \app
is better to use a controller ProductController and redefined yours functions
If your products model is Product then you have typo in your code.
Route::get ( '/', function () {
$mydatabase = Products::paginate(25);
return view ( 'search' )->withproducts($mydatabase);
} );
You have a typo in your code change products::paginate to Product::paginate()
Hope this helps
Try replacing products::paginate with \App\products::paginate?
Laravel is namespaced, therefore it cannot find a class just by the correct name.
Laravel 5 promotes the use of namespaces for things like Models and Controllers. Your Model is under the App namespace, so your code needs to call it like this:
Route::get('/', function(){
$myDatabase= \App\Products::paginate(25);
});
Solved! Big Thanks guys for your Help!
I have just must added
use App\Product;
to my web.php file and works great!
Related
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>Bearbeiten</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);
}
}
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.
I am working on an assignment for Uni however I've ran into a snag paginating my comments field. I have put my Controller, Model and View bellow(in that order)
<?php
namespace App\Http\Controllers;
use App\Comment;
use Illuminate\Http\Request;
class CommentController extends Controller
{
const COMMENTS_PER_PAGE = 5;
public function index () {
$comments = Comment::paginate (self::COMMENTS_PER_PAGE);
return view ('index') -> with (['comments' => $comments]);
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show(Comment $comment)
{
//
}
public function edit(Comment $comment)
{
//
}
public function update(Request $request, Comment $comment)
{
//
}
public function destroy(Comment $comment)
{
//
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public static function paginate(int $COMMENTS_PER_PAGE)
{
}
}
{{--#extends('layout.master)--}}
{{--#section('content')--}}
<div class="container main-table">
<div class="box">
<h1 class="title">Guestbook Comments</h1>
#if (count ($comments) > 0)
<table class="table is-striped is-hoverable">
<thead>
<tr>
<th>User</th>
<th>Comment</th>
<th>Date</th>
<th>Likes</th>
</tr>
</thead>
<tbody>
#foreach ($comments as $c)
{{--declaring the comments--}}
<tr>
<td>{{ $c -> name }}</td>
<td>{{ $c -> comment }}</td>
<td>{{ $c -> created_at -> format ('D jS F') }}</td>
<td>{{ $c -> likes }}</td>
</tr>
#endforeach
</tbody>
</table>
{{--looking at pagination--}}
{{ $comments -> links() }}
#else
<div class="notification is-info">
<p>
The Guestbook is empty. Why not add a comment?
</p>
</div>
#endif
</div>
</div>
{{--#endsection--}}
I managed to get it to display the comments before changing to pagination. After doing this I ran into issues getting it to display. I don't get an error I just get a blank page as if nothing is wrong. It doesn't show any of my headings or text that is not from my comments table.
Has anyone got any ideas about why this is?
Any help would be greatly appreciated :D
Update 17:44 13/11/19
Just realised that the link was going to the wrong page but just now figured out that the count function is having and issue as it says that there is no relevant ARRAY ("Facade\Ignition\Exceptions\ViewException
count(): Parameter must be an array or an object that implements Countable (View: C:\XAMPP\htdocs\Assignment\resources\views\comment\comments.blade.php) ")
Does anyone know why this is?
I thought it would just list comments 1 by 1 up until it reads out 5 comments.
Any ideas on how to fix this? :)
change {{ $comments -> links() }} & try this
{!! $comments->render() !!}
I would recommend to paginate like this.
public function index () {
const COMMENTS_PER_PAGE = 5;
$comments = Comment::paginate(self::COMMENTS_PER_PAGE);
return view('index', compact('comments'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
and also, change
{!! $comments->links() !!}
to
{!! $comments->render() !!}
{!! $comments->appends(Request::except('page'))->render() !!}
When i run my webpage it's can run normally but i can't search.
I need to search for data by those data from different table and when i search data it show error
Undefined property: stdClass::$user (View:
C:\xampp\htdocs\ff\Laravel-Webboard-Workshop-master\resources\views\group\index.blade.php)
and created_at->diffForHumans() too it show error:
Call to a member function diffForHumans() on string (View: C:\xampp\htdocs\ff\Laravel-Webboard-Workshop-master\resources\views\group\index.blade.php)
$group is in table groups no problem.
$group->user->name is about table users has problem:
Undefined property: stdClass::$user
and $group->created_at->diffForHumans() has problem:
Call to a member function diffForHumans() on string
view group\index.blade.php
<div class="container">
<div class="row">
<div class="col-md-12">
<form action="/search" method="get">
<div>
<button type="submit" class="btn btn-primary" style="float:right;">Search</button>
<a style="float:right;">
<input type="search" name="search" class="form-control" >
</a>
</div>
</form>
</div>
<br><br>
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading" style="font-size: 18px;">Home</div>
<div class="panel-body">
<table class="table table-striped table-linkable table-hover">
<thead>
<tr>
<th class="text-center">Group</th>
<th class="text-center">Posted By</th>
<th class="text-center">Posted At</th>
</tr>
</thead>
<tbody>
#foreach($groups as $group)
<tr onclick="document.location.href = '{{ route('topic.index', $group->id) }}'">
<td>{{ $group->title }}</td>
<td class="text-center">{{ $group->user->name }}</td> <!--error for search-->
<td class="text-center">{{ $group->created_at->diffForHumans() }}</td> <!--error for search-->
</tr>
#endforeach
</tbody>
</table>
<div class="text-center"> {!! $groups->links(); !!} </div>
</div>
</div>
</div>
</div>
</div>
Controller GroupController.php
class GroupController extends Controller
{
public function search(Request $request)
{
$search = $request->get('search');
$groups = DB::table('groups')->where('title', 'like', '%'.$search.'%')->paginate(5);
//$users = DB::table('users')->where('name', 'like', '%'.$search.'%')->paginate(5);
return view('group.index', ['groups' => $groups] );
}
}
Route
Route::get('/search','GroupController#search');
How should I fix it ??
Let's tackle one problem at the time.
Undefined property: stdClass::$user (View: C:\xampp\htdocs\ff\Laravel-Webboard-Workshop-master\resources\views\group\index.blade.php)
This is because you are trying to access the property user on each Group object:
$group->user->name
// ^^^^
I assume that you're trying to access a relationship on the Group model. So you can do your query using Eloquent instead of the Query Builder. To do so, you need to make use of your Group and User models (check the docs related to Models documentation):
# GroupController.php
class GroupController extends Controller
{
public function search(Request $request)
{
$search = $request->get('search');
// $groups = DB::table('groups')->where('title', 'like', '%'.$search.'%')->paginate(5);
$groups = Group::with('user')->where('title', 'like', '%'.$search.'%')->paginate(5);
// ^^^^^^^^^^^^^^^^^^
return view('group.index', ['groups' => $groups] );
}
}
Note: in order for this to work, you need to have the user() relationship defined in your Group model (check the Relationship section of the documentation for more info):
# Group.php
Class Group extends Model {
public function user()
{
return $this->hasOne(User::class); // for example
}
}
Call to a member function diffForHumans() on string (View: C:\xampp\htdocs\ff\Laravel-Webboard-Workshop-master\resources\views\group\index.blade.php)
This is because you need to call diffForHumans() on a Carbon instance. Given that you are using the Query Builder, the timestamps (created_at/updated_at) aren't casted as Carbon instances, they are just strings at the moment. That is why the error is thrown.
Now that we updated the query to use Eloquent instead of the Query Builder, Laravel will cast your timestamps to Carbon instances automatically, so now if you dd($group->created_at) you will notice that is an instance of the Carbon class. Have a look at the Date Casting section of the documentation.
Hello i have two models Adress and Kontokorrent they have a one to one relationship. I would like to make a search function and search after Adress and Kontokorrent columns
My models:
Adress Model
class Adress extends Model
{
protected $table = "Adressen";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchAdress($query, $searchTerm)
{
return $query->where('LieferOrt', 'LIKE', '%'.$searchTerm.'%')
->orWhere('Name1', 'LIKE', '%'.$searchTerm.'%')
->orWhere('LieferStrasse', 'LIKE', '%'.$searchTerm.'%');
}
public function kontokorrent()
{
return $this->hasOne(Kontokorrent::class, 'Adresse');
}
}
Kontokorrent Model
class Kontokorrent extends Model
{
protected $table = "Kontokorrent";
protected $primaryKey = 'Adresse';
public $timestamps = false;
public function scopeSearchKto($query, $searchTerm)
{
return $query->where('Kto', 'LIKE', '%'.$searchTerm.'%');
}
public function adress()
{
return $this->belongsTo(Adress::class, 'Adresse');
}
}
Controller
class AdressesController extends Controller
{
public function index(Request $request)
{
$searchTerm = $request->input('searchTerm');
$adresses = Adress::whereHas('kontokorrent', function($query) use($searchTerm) {
$query->where('KtoArt', 'D')
->searchKto('K75688'); // this is working
// -> searchKto($searchTerm); this is NOT working
})->orderBy('Name1')
->searchAdress($searchTerm)
->paginate(60);
return view('adresse.index', compact('adresses', 'searchTerm'));
}
}
The search function in Adress model is working. Now i would like to search after the customer ID (Kto) in Kontokorrent. So i made a scope in Kontokorrent and chain it to the contoller search function.
->searchKto('K75688') .... this is working i get a result
->searchKto($searchTerm) .... this is not working when i entry the customer id in my input field and hit enter. I get a 0 row table.
View
#section('content')
<div class="row">
<div class="col-xs-12 col-md-12">
<form role="search" method="GET" action="/adresses">
<div class="input-group">
<input type="text" class="form-control" name="searchTerm" value="{{ isset($searchTerm) ? $searchTerm : '' }}" placeholder="Suche nach Name, Straße, Ort">
<div class="input-group-btn">
<button type="submit" class="btn btn-search btn-default">
Suchen...
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Straße</th>
<th>Ort</th>
<th>PLZ</th>
<th>Land</th>
</tr>
</thead>
<tbody>
#if(count($adresses) > 0)
#foreach($adresses as $adress)
<tr>
<th scope="row">{{ $loop->iteration }}</th>
<td>
{{$adress->Anrede}} {{ $adress->Name1}}
#if($adress->kontokorrent)
<small>{{ $adress->kontokorrent->Kto }}</small>
#endif
</td>
<td>{{ $adress->LieferStrasse }}</td>
<td>{{ $adress->LieferOrt }}</td>
<td>{{ $adress->LieferPLZ }}</td>
<td>{{ $adress->LieferLand }}</td>
</tr>
#endforeach
#else
<tr><td colspan="6" class="text-center">Kein Eintrag gefunden.</td></tr>
#endif
</tbody>
</table>
</div>
</div>
{{ $adresses->appends(['searchTerm' => $searchTerm])->links() }}
#endsection
I don't understand why I get an empty table.
I have search box for my Laravel project it seems working because after request I'll get http://project.dev/search?q=fifth but nothing prints in blade template.
here is my SearchController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
class SearchController extends Controller
{
public function index() {
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
$yesterday_posts = Post::whereRaw('Date(created_at) = DATE_ADD(CURDATE(), INTERVAL -1 DAY)')->count();
$weekly_posts = Post::whereBetween( 'updated_at', [Carbon::today()->startOfWeek(), Carbon::today()->endOfWeek()] )->count();
$monthy_posts = Post::whereRaw('MONTH(created_at) = ?', Carbon::today()->month)->count();
$q = Input::get('q');
$posts = Post::where('title','LIKE','%'.$q.'%')->orWhere('slug','LIKE','%'.$q.'%')->get();
if(count($posts) > 0)
return view('theme.search', compact('posts', 'countTodayOrders', 'yesterday_posts', 'weekly_posts', 'monthy_posts'))->withQuery ( $q );
else return view ('theme.index')->withMessage('No Details found. Try to search again !');
}
}
Here is my search form
<!-- search box -->
<form action="/search" method="get" role="search">
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search users"> <span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<!-- search box -->
Here is my routes
Route::any('/search', ['uses' => 'SearchController#index', 'as' => 'search.index']);
Here is my blade
#extends('layout.app')
#section('content')
<div class="col-md-9 technology-left">
<div class="tc-ch wow fadeInDown" data-wow-duration=".8s" data-wow-delay=".2s">
#if(isset($details))
<p> The Search results for your query <b> {{ $query }} </b> are :</p>
<h2>Sample User details</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Post</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->name}}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
</div>
</div>
#endsection
where is my mistake?
Update
Now I have search box which is work and show data with pagination but when i search for example for word sample which i have 3 posts with that title in first page of results I'm getting results like this:
first page
But when i go to second page everything changes!
second page
Why?
Ok guys i got it thanks, the issue was withQuery method as i used compact i shouldn't use with i just added it to `compact and now it's working. but what about counting the results? how can i pass the number of founded result in blade?