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?
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 have referral code search box that query referral codes. this code must be available before user can register. So basically on Auth.register I have two boxes, firs t box holds the referral code search box and the other one is the registration box. My goal is to hide first the registration box and appear only if the code has found.
RegisterController
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
if (count ( $referral ) > 0)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided is not existing.' );
}
register.blade.php
<!-- THIS IS THE FIRST BOX THAT HOLDS THE CODE SEARCH BOX -->
<div class="card mx-4">
<div class="card-body p-4">
<h1>Referral Code</h1>
<p class="text-muted">Please provide the referral code given to you by your collector</p>
#if(isset($message))
<div class="alert alert-success">
{{ $message }}
</div>
#endif
{!! Form::open(['method' => 'GET', 'url' => '/register', 'class' => 'form-inline my-2 my-lg-0', 'role' => 'search']) !!}
<div style="width: 100%;">
<input type="text" class="form-control" name="search" style="width: 100%;" placeholder="Enter your referral code here!">
</div>
<div style="width: 150px; margin: auto; margin-top: 20px; ">
<button class="btn btn-success btn-default" type="submit">
<i class="fa fa-search"></i> Check Availability
</button>
</div>
{!! Form::close() !!}
</div>
</div>
<!-- THIS IS THE 2ND BOX THAT HOLDS THE REGISTRATION FORM -->
#if(isset($details))
<div class="card mx-4">
<div class="card-body p-4">
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
... the rest of registration form ...
</div>
</div>
#endif
My problem now is, the #details is displaying the current rows of "Referrals"
Is there a way that query from this line,
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
should only display if the result is match from $keyword?
because currently the page is look like this
Thanks!
I think you want something like to match the keyword against your database. So instead of partial matching use exact matching.
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where([
['code', $keyword],
['status', 0]
])->first();
if ($referral)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided does not exist or already used.' );
}
And in view you need not to use the following lines.
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
Just add your registration form after #if(isset($details)).
Its weird how you are doing this. You can use AJAX to do it in a single page
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.
I have been getting this error all day and cant seem to get it right. my goal is basically to update a user in the admin_users table, in order to change their rolls.
this is the Error.
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message Laravel 5.7
Web.php
Route::get('/dashboard', 'DashboardController#dashboard');
Route::post('/admin_users', 'AdminUController#admin_users')->name('admin_users.update');
Route::get('/admin_users', 'AdminUController#admin_users')->name('admin_users');
This is the Controller AdminUController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use Mail;
use Session;
use Gate;
use App\Admin_users;
class AdminUController extends Controller
{
public function admin_users(){
if(!Gate::allows('isUser')){
if(!Gate::allows('isAdmin')){
abort(404,"Sorry, There is nothing to see here!");
}
}
// data from users table to be passed to the view
$admin_users = Admin_users::all();
$title = 'Earn, Invest, Save, and Learn with the Invo App';
return view('admin_users', ['admin_users' => $admin_users])->with('title',$title);
}
public function update(Request $request, Admin_users $admin_users){
$admin_users->email = $request->email;
$admin_users->user_type = $request->user_type;
$admin_users->save();
session()->flash('User account has been updated!');
return redirect()->back();
}
}
This is the Model Admin_users.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Admin_users extends Model
{
protected $guarded=[];
//public function admin_users(){
// }
}
This is the blade template admin_users.blade.php
#extends('layouts.app_dashboard')
#section('content')
<div class="col-md-12">
<div class="margin-top card strpied-tabled-with-hover">
<div class="card-header ">
<h4 class="card-title">Invo Admin Users</h4>
<p class="card-category">Click to edit each user</p>
<a href="{{ route('register') }}" class="btn btn-primary margin-top">
Add New User
</a>
</div>
<div class="card-body table-full-width table-responsive">
<table class="table table-hover table-striped">
<thead>
<tr><th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Password </th>
<th>User Access</th>
</tr></thead>
<tbody>
#foreach ($admin_users as $user)
#if(session()->has('message'))
<div class="alert alert-success">
{{session()->get('message')}}
</div>
#endif
<form method="POST" action="{{route('admin_users.update', $user->id)}}">
#csrf
#method('put')
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="{{$user->email}}">
</td>
<input type="file" class="custom-file-input" value="" placeholder="{{$user->email}}">
<td>*********</td>
<td>
<select class="selectpicker">
#if(Auth::id() == $user->id)
<option selected value="{{$user->user_type}}">{{$user->user_type}}</option>
<option value="user">user</option>
#else
<option selected value="{{$user->user_type}}">{{$user->user_type}}</option>
<div role="separator" class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Change User Type to</a>
#if($user->user_type == 'admin')
<option value="user">user</option>
#else
<option value="admin">admin</option>
#endif
#endif
</select>
</td>
<td>
<button type="submit" class="btn btn-primary">
Update
</button>
</td>
</tr>
</form>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
I can't comment for clarification but is it not because you need to allow the put method through the routes? :)
Route::put($uri, $callback);
from the docs here:
https://laravel.com/docs/5.7/routing
So I believe the answer to be:
Route::put('/admin_users', 'AdminUController#admin_users')->name('admin_users.update');
Put isn't a method I use a massive amount though so I'm talking purely from my experience with Laravel rather than working with put requests themseleves so apologies if I've gone down the wrong path :)
The main reason you're getting this error is because you set your form to submit with a PATCH method and you've set your route to look for a PUT method.
you could also set your route to:
Route::match(['put', 'patch'], '/admin_users/update/{id}','AdminController#update');
Alternatively, you can use php artisan make:controller AdminUController --resource
Laravel resource routing assigns the typical "CRUD" routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for admin_users
Then your resource route would look something like:
Route::resource('admin_users', 'AdminController');
I have Tried to fetch data from MySQL db using eloquent in my laravel application it shows Parse Error here my code :
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class design extends Model {
//Table Name
protected $table='designs';
//Primary key
public $primarykey='id';
// TimeStamp
public $timestamps=true;
}
Controller Page:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\design;
class designController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$design=design::all();
//$design = design::select('Design No','Design Name','Chain Weight/Length','status')->where('status','=','Active')->get();
return view('pages.design')->with('design',$design);
}
}
page for listing:
the error occurring while using for-each
#extends('layouts.layout')
#section('content')
<div class="main">
<div class="container col-md-12 col-sm-12 col-xs-12">
<h2 class="text-center">Designs</h2>
#if(count($design)>=1)
<h2>Done</h2>
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Design No</th>
<th>Design Name</th>
<th>Weight/Lenght</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($design as $design)
<tr>
<td>{{$design->Design No}}</td>
<td>{{$design->Design Name}}</td>
<td>{{$design->Chain Weight/Length}}</td>
<td>
<button type="button" class="btn btn-warning">Edit</button>
<button type="button" class="btn btn-danger">{{$design->status}}</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
#endsection
it doesn't allow space in column name it should be in lower cases as design_no , design_name in your DB
and then fetch as
#foreach($design as $new_designs)
<td>{{$new_designs->design_no }}</td>
// and so on
#endforeach
Hope it will work.
try this
{{$design->{'Design No'} }}
Yous should try this:
Controller Page
public function index()
{
//
$designs=design::all();
return view('pages.design',compact('designs'));
}
View Page
#foreach($designs as $design)
<tr>
<td>{{$design->Design_No}}</td>
<td>{{$design->Design_Name}}</td>
<td>{{$design->Chain_Weight/Length}}</td>
<td>
<button type="button" class="btn btn-warning">Edit</button>
<button type="button" class="btn btn-danger">{{$design->status}}</button>
</td>
</tr>
#endforeach