Laravel Eloquent Paginate Doesn't Exist Error - php

I'm trying to set pagination in a Laravel blade/view but it's showing an error with this message below:
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::paginate does not exist.
Controller
public function view()
{
$user = Auth::user();
$basic_info = User::find($user->id)->basic_info;
$category = Category::all()->paginate(10);
return view('admin.article.category-view')->with(['user' => $user, 'basic_info' => $basic_info, 'category' => $category]);
}
View Blade (admin.article.category-view)
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>Category Name</th>
</tr>
</thead>
<tbody>
#foreach($category as $cat)
<tr>
<td>{{ $cat->name }}</td>
</tr>
#endforeach
</tbody>
</table>
{{ $category->links() }}
</div>

Using paginate method on the query builder or an Eloquent query only, not on collection, like so:
public function view()
{
$user = Auth::user();
$basic_info = User::find($user->id)->basic_info;
$category = Category::paginate(10);
return view('admin.article.category-view')->with(['user' => $user, 'basic_info' => $basic_info, 'category' => $category]);
}

You need to remove all():
$category = Category::paginate(10);
When you're using all() you get all the rows from the table and get a collection
You can only invoke "paginate" on a Query, not on a Collection.

Related

How to pass a Static value with search results in a Laravel Controller

I have the following method defined in my controller. I want to pass the value of $title along with the search results so that it can be displayed at the top of the blade page, but I am unsure how to do it.
public function index_sog(Request $request)
{
$title = 'Standard Operating Guideline';
return view('knowledgebase.index', [
'kbase' => Knowledgebase::orderBy('category', 'asc')
->filter(request(['tags', 'search']))
->where('type','SOG')
->paginate(20),
'search' => $request->input('search')
]);
}
My output...
<h4>{{//TITLE SHOULD GO HERE//}}</h4>
<div class="panel-container show">
<div class="panel-content">
#foreach ($kbase->groupBy('category') as $category => $group)
<table class="table">
<tr>
<th colspan="3" class="text-center bg-fusion-50"><strong>{{ $category }} <strong></th>
</tr>
#foreach ($group as $kb)
<tr>
<td>{{ $kb->title }}</td>
<td></td>
<td></td>
</tr>
#endforeach
</table>
#endforeach
</div>
</div>
ADD on return variables. And you can use on blade like {{ $title }}
> return view('knowledgebase.index', [
> 'kbase' => Knowledgebase::orderBy('category', 'asc')
> ->filter(request(['tags', 'search']))
> ->where('type','SOG')
> ->paginate(20),
> 'search' => $request->input('search'),
> 'title' => $title
> ]);
For example you can do this way:
return view('knowledgebase.index', [
'kbase' => Knowledgebase::orderBy('category', 'asc')
->filter(request(['tags', 'search']))
->where('type','SOG')
->paginate(20),
'search' => $request->input('search')
])->with('title', $title);
By adding the ->with() method to the return.
You can also put it inside the array of variables that you already have in return.
And then in your view:
<h4>{{ $title }}</h4>

When I am logged in I want to see all users' information, other than the logged-in user, in Laravel?

home blade
<div class="card-header">Total Users: {{ $users->count() }} </div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<table class="table table-dark table-striped">
<tr>
<th>SL</th>
<th>Name</th>
<th>Email</th>
<th>Created at</th>
</tr>
#foreach($users as $user)
<tr>
<td>{{$loop->index +1}}</td>
<td>{{ $user-> name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->created_at->diffForHumans()}}</td>
</tr>
#endforeach
</table>
</div>
HomeController
public function index()
{
$users = User::all();
return view('home', compact('users'));
}
When I am logged in I want to see all the other users information in a table other than the logged-in user in Laravel. How can I accomplish that?
While the accepted answer works, a nicer approach would be to make use of Laravel's except() Collection method:
The except method returns all items in the collection except for those with the specified keys
Your query then just returns all users except the currently logged in user to your view. No logic in your view, no other changes required:
public function index()
{
$users = User::all()->except(Auth::id);
return view('home', compact('users'));
}
If you pass the current user's ID along with the user list you can simply test against that ID.
public function index()
{
$users = User::all();
return View::make('home', array(
'users' => $users,
'user_id' => Auth::id()
));
}
#foreach($users as $user)
#if ($user->id != $user_id)
<tr>
<td>{{$loop->index+1}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->created_at->diffForHumans()}}</td>
</tr>
#endif
#endforeach

Laravel: one-to-many retrieving single record in view

I'm currently learning Laravel 5.6. So my problem is this, I have the following Model:
class Tour extends Model
{
//
protected $fillable = [
'name',
'price',
'category',
'overview',
'activity',
'exclusion',
'inclusion',
'policies',
'guide_id',
'province_id'
];
public function tourImages(){
return $this -> hasMany('App\TourImage');
}
}
class TourImage extends Model
{
//
protected $fillable = [
'name',
'path',
'tour_id'
];
public function tour(){
return $this -> belongsTo('App\Tour');
}
}
So 1 Tour can have multiple TourImages. What i want to do is that i want to print out all the tours on the index page. But i only want to take one TourImage file to display for each tour. I return only array of all tours from controller. Is there a way that i can retrieve image directly on the blade view without returning more variable from the controller?
Here's what I write for my index method:
public function index($province_id = null)
{
$tours = Tour::where('province_id', $province_id)->get();
return view('tours.index', ['tours' => $tours]);
}
Here's my index view:
#extends('layouts.app')
#section('content')
<div class="col-md-8 offset-md-2">
<br/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Picture</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
#foreach($tours as $tour)
<tr>
<th scope="row">{{ $tour->id }}</th>
<td>{{ $tour->name }}</td>
<td><img src="/storage/{{ $tour->tourImages->path }}" width="200px"/></td>
<td>{{ $tour->price }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
you can pass one image of each tour by this code :
$tours=Tour::with(['tourImages'=>function($query){
$query->first();
}])->get();
and in view:
#foreach($tours as $tour)
#if ($tour->tourImages->count())
<img src="/storage/{{ $tour->tourImages[0]->path }}" width="200px"/>
#endif
#endforeach
you need to use with() to get records.like this.
$tours = Tour::with('tourImages')->where('province_id', $province_id)->get();
You can add new relation in your Tour model like
public function latestTourImage() {
return $this->hasOne('App\TourImage')->latest();
}
Then you can fetch it using this in your controller file
$tours = Tour::with('latestTourImage')->where('province_id', $province_id)->get();
and then you can print it in your blade file like
$tour->latestTourImage->path

How to get data from database to view page in laravel?

I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).
Here is the code of my project:
HTML:
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th><strong>No</strong></th>
<th><strong>Nama Petani</strong></th>
<th><strong>Alamat</strong></th>
<th><strong>No. Handphone</strong></th>
<th><strong>Lokasi</strong></th>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
</div>
PHP:
In my listpetani.blade.php I have an empty table and I want to show data from database tbl_user:
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
});
And the table in my page: view in browser
I want to show all the data from database into my view in laravel 5.4. Can anybody help me?
[SOLVE]
Thank you guys, I already solve this problem
This is the solved code
web.php (routes)
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->get();
return view('listpetani', ['petani' => $petani]);
});
and in my listpetani.blade.php
#foreach($petani as $key => $data)
<tr>
<th>{{$data->id_user}}</th>
<th>{{$data->nama_user}}</th>
<th>{{$data->alamat}}</th>
<th>{{$data->no_telp}}</th>
<th>{{$data->id_lokasi}}</th>
</tr>
#endforeach
You can get data from database in view also
#php( $contacts = \App\Contact::all() )
#php( $owners = \App\User::all())
<select class="form-control" name="owner_name" id="owner_name">
#foreach($contacts as $contact)
<option value="{{ $contact->contact_owner_id }}">{{ $contact->contact_owner }}</option>
#endforeach
</select>
It would be better if you pass data from controller to view.
return view('greetings', ['name' => 'Victoria']);
Checkout the docs:
https://laravel.com/docs/8.x/views#passing-data-to-views
Alternatively you can use #forelse loop inside laravel blade
#forelse($name as $data)
<tr>
<th>{{ $data->id}}</th>
<th>{{ $data->name}}</th>
<th>{{ $data->age}}</th>
<th>{{ $data->address}}</th>
</tr>
#empty
<tr><td colspan="4">No record found</td></tr>
#endforelse
In your controller:
$select = DB::select('select * from student');
return view ('index')->with('name',$select);
In Your view:
#foreach($name as $data)
<tr>
<th>{{ $data->id}}</th> <br>
<th>{{ $data->name}}</th> <br>
<th>{{ $data->age}}</th> <br>
<th>{{ $data->address}}</th>
</tr>
#endforeach
I hope this can help you.
#foreach($petani as $p)
<tr>
<td>{{ $p['id_user'] }}</td>
<td>{{ $p['username'] }}</td>
<td>{{ $p['alamat'] }}</td>
<td>{{ $p['no_telp'] }}</td>
<td>{{ $p['id_lokasi'] }}</td>
</tr>
#endforeach
**In side controller you pass this **:
$petanidetail = DB::table('tb1_user')->get()->toArray();
return view('listpetani', compact('petanidetail'));
and Inside view you use petanidetail variable as follow:
foreach($petanidetail as $data)
{
echo $data;
}
I hope you already know this, but try use Model and Controller as well,
Let the route take the request, and pass it to controller
and use Eloquent so your code can be this short:
$petani = PetaniModel::all();
return view('listpetani', compact('petani));
and instead using foreach, use forelse with #empty statement incase your 'listpetani' is empty and give some information to the view like 'The List is Empty'.
Try this:
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
on your view iterate $petani using foreach() like:
foreach($petani as $data)
{
echo $data->id_user; // $petani is a Std Class Object here
echo $data->username;
}
Other answers are correct, I just want to add one more thing, if your database field has html tags then system will print html tags like < p > for paragraph tag. To remove this issue you can use below solution:
You may need to apply html_entity_decode to your data.
This works fine for Laravel 4
{{html_entity_decode($post->body)}}
For Laravel 5 you may need to use this instead
{!!html_entity_decode($post->body)!!}

Laravel - paginated model sort link in blade view

In laravel 5.2 I have a paginated table of a model.
#CityController
public function index(Request $request){
$cities = City::orderBy('name');
return view('pages.city.index', ["cities" => $cities ->paginate(25)]);
}
This works fine, but when I try to sort the results inside the blade view does not work.
#index.blade.php
<table>
<thead>
<tr class="sui-columnheader">
<th class="sui-headercell" data-field="Id">
Id
</th>
</thead>
<tbody class="list">
#foreach ($cities as $city)
<tr class="sui-row">
<td class="sui-cell id">{!! $city->id !!}</td>
</tr>
</tbody>
</table>
When I click the sort button just reloads the page but no sort is applied.
Is because of the "orderBy" clause?
How can I make it work and defaults to order by name?
Am I missing something?
Something like this perhaps. You would want to make sure you limit what can be passed to that orderBy. A URL like "...something?sort=blah" would cause orderBy('blah'), which your table doesn't have, which will cause a DB error.
public function index(Request $request)
{
$cities = City::orderBy($request->input('sort', 'name'))->paginate(25);
return view('pages.city.index', ['cities' => $cities]);
}
{{ $cities->appends(Request::query())->render() }}
Just giving you a functional example, though you will have to adjust based on your own rules.
The appends is just allowing you to continue to paginate based on the current sorting, by passing the sort option via the query string of the pagination links.
Update:
Using your example where there is a default, but imagining there can be more than just 1 other field to sort by:
$sort = trim($request->input('sort'));
// if it is in the acceptable array use it, otherwise default to 'name'
$sort = in_array($sort, ['id', ...]) ? $sort : 'name';
$cities = City::orderBy($sort)->paginate(25);
<table>
<tr>
<th>ID</th>
<th>NAME</th>
...
</tr>
#foreach ($cities as $city)
<tr>
<td>{{ $city->id }}</td>
<td>{{ $city->name }}</td>
...
</tr>
#endforeach
...
{{ $cities->appends(Request::query())->render() }}
Just an example, you can do this how you would like.

Categories