Paginate eager loaded relationships results - php

i am trying to paginate a relationship result set by using a code very similar to this
<?php
class MainController extends Controller {
public function show(Main $main)
{
$main = $main->with([
'secondaryMorph' => function ($query) {
$query->orderBy('ocurred_at');
$query->paginate(50);
}
])->first();
return view('main.show')->with(compact('main'));
}
}
But when this part of the view's code run a exception is thrown:
<td colspan="3">Mostrando {{ $secondary->count() }} de {{ $secondary->total() }}</td>
<td colspan="3">{{ $secondary->links() }}</td>
ErrorException (E_ERROR)
Method Illuminate\Database\Eloquent\Collection::total does not exist.
How can i use eager loading with pagination?

How about :
$main = $main->first();
$secondary = $main->secondaryMorph()->paginate();
return view('main.show')->with(compact('main','secondary'));
And then in blade :
<td colspan="3">Mostrando {{ $secondary->count() }} de {{ $secondary->total() }}</td>
<td colspan="3">{{ $secondary->links() }}</td>

Related

Why do I get a "Trying to get property of non-object" error when using Sortable package in Laravel?

I've encountered a problem with the Kyslik\Column-sortable package for Laravel which has frustrated me for weeks now. :)
The sorting links displays correctly, but when I click on one of the sorting links, I get the following error:
🧨 Trying to get property 'title' of non-object (View: C:\wamp64\www\GeekCollector\resources\views\Lp\show.blade.php)
What's even more strange is that the route goes to the BrowseResults view, but the message sais that the error was encountered in the Show view.
If I remove all the sortable related stuff from the BrowseResults view, the Show view works perfectly.
Here is my model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;
use Kyslik\ColumnSortable\Sortable;
class Lp extends Model
{
use HasFactory;
use Sortable;
public $sortable = ['title', 'artist', 'year'];
}
Here is my BrowseResults controller method:
public function browseResults(Request $request)
{
$chosenCategory = $request->category;
$lps = Lp::where('category','like','%'.$chosenCategory.'%');
$result = $lps->sortable('title')->paginate(5);
return view('Lp.browseResults', compact('result'));
}
And here is my blade view:
<x-app-layout>
<x-slot name="header">
<h1 class="font-semibold text-xl text-gray-800 leading-tight">
Lp-skivor
</h1>
</x-slot>
#sortablelink('title')
#sortablelink('artist')
#sortablelink('year')
<table>
<tr>
<td>Titel</td>
<td>Artist</td>
<td>Kategori</td>
<td>Plats</td>
<td>Position</td>
</tr>
#foreach ($result as $lp)
<tr>
<td>
{{ $lp->title }}
</td>
<td>{{ $lp->artist }}</td>
<td> {{ $lp->category }}</td>
<td>{{ $lp->place }}</td>
<td>{{ $lp->position }}</td>
<td>
Uppdatera
</td>
<td>
<form action="{{ route('lp.destroy', $lp->id) }}" method="post">
#csrf
#method('DELETE')
<button type="submit">Ta bort</button>
</form>
</td>
</tr>
#endforeach
</table>
{!! $result->appends(\Request::except('page'))->render() !!}
</x-app-layout>
The route looks like this:
Route::post('/lp/browse-results', [LpController::class, 'browseResults'])->name('lp.browseResults');
Thanks very much in advance for your help!
All the best!

Laravel one to many relationship doesn't work anymore

This relationship of mine was working last week, but it stopped working.
When i use it in my blade template it says: Trying to get property 'name' of non-object.
The weird thing is, when i use it in dd() it perfectly shows, but when i try to print it in blade, it doesn't.
Code PaymentsController
<?php
namespace App\Http\Controllers;
use App\Betaling;
use App\Settings;
use Illuminate\Http\Request;
class PaymentsController extends Controller
{
public function index(){
$user_id = auth()->user('id');
$role = auth()->user()->role_id;
$settings = Settings::where('user_id', $user_id->id)->first();
if ($role === 1){
$totaalaantalbetalingen = Betaling::all();
} else {
$totaalaantalbetalingen = Betaling::where('user_id', $user_id->id)->get();
}
return view('payments.index', compact(['totaalaantalbetalingen','role', 'user_id', 'settings']));
}
}
Code index.blade.php
#foreach($totaalaantalbetalingen as $betaling)
<tr>
<th scope="row">{{ $betaling->id }}</th>
#if($role === 1)
<td>{{ $betaling->user->name }} </td>
#endif
<td>{{ $betaling->customer->name }}</td>
<td>{{ $betaling->reference}}</td>
<td>€ {{ $betaling->amount}}</td>
<td>{{ $betaling->time_of_invoice }}</td>
<td>{{ $betaling->time_of_payment }}</td>
<td></td>
<td>{{ $betaling->user->location }}</td>
</tr>
#endforeach
code User model:
public function betalingen(){
return $this->hasMany(Betaling::class);
}
code Betaling model:
public function customer(){
return $this->belongsTo(User::class);
}
public function user(){
return $this->belongsTo(User::class);
}
code Customer model:
public function betaling(){
return $this->hasMany(Betaling::class);
}
pass auth()->user()->id and in blade file check !empty($totaalaantalbetalingen)
code User model:
public function betalingen(){
return $this->hasMany('App\Betaling','betalingenid','id'); // pass foreign key for ex.
}
code Betaling model:
public function customer(){
return $this->belongsTo('App\User','customer_id','id');// pass foreign key for ex.
}
public function user(){
return $this->belongsTo('App\User','user_id','id');// pass foreign key for ex.
}
code Customer model:
public function betaling(){
return $this->hasMany('App\Betaling','customer_id','id');// pass foreign key for ex.
}
Controller
public function index(){
$user_id = auth()->user()->id;
$role = auth()->user()->role_id;
$settings = Settings::where('user_id', $user_id)->first();
if ($role == 1){
$totaalaantalbetalingen = Betaling::all();
} else {
$totaalaantalbetalingen = Betaling::where('user_id', $user_id)->get();
}
return view('payments.index', compact(['totaalaantalbetalingen','role', 'user_id', 'settings']));
}
blade.php
#if(!empty($totaalaantalbetalingen) && isset($totaalaantalbetalingen))
#foreach($totaalaantalbetalingen as $betaling)
<tr>
<th scope="row">{{ $betaling->id ?? '' }}</th>
#if($role === 1)
<td> {{ $betaling->user->name ?? '' }} </td>
#endif
<td> {{ $betaling->customer->name ?? '' }} </td>
<td> {{ $betaling->reference ?? '' }} </td>
<td> € {{ $betaling->amount ?? '' }} </td>
<td> {{ $betaling->time_of_invoice ?? '' }} </td>
<td> {{ $betaling->time_of_payment ?? '' }} </td>
<td> </td>
<td> {{ $betaling->user->location ?? '' }} </td>
</tr>
#endforeach
#endif

Paginating in Laravel

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() !!}

Fetching data from Database in Laravel

I want to fetch data from database table named 'users' and display the output in a table.
I have written below code but it's not working.
I am using Laravel 5.5
#extends('layouts.app')
#section('content')
<div class="container">
<h2>Admin Panel</h2>
<p>Data of the Registered Users.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
$users = DB::table('users')->select('id','name','email')->get();
#foreach($users as $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
Error: Undefined Variable: users
The problem is that you're trying to mix PHP within your (Blade) template. Although it is possible to do so with #php directives, this is bad practice: your view should not contain any business logic.
Ideally you want to pass this data from your controller. It should look something like this:
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
return view('some-view')->with('users', $users);
}
}
Read more on passing data to views here.
You are doing it all wrong, the point of MVC design is to have your controllers do the application logic, your views to represent a representation of that data and models to contain the data you need, in your case you are missing the point completely by using DB::table inside of your view, so here is an example code which you might need to correct a bit:
The example below doesn't show MVC pattern since the data is passed from inside a closure of a route
web.php
Route::get('/', function () {
$users = DB::table('users')->select('id','name','email')->get();
return view('VIEW-NAME-HERE', compact('users'));
});
view.blade.php
#foreach($users as $user)
{{ $user->id }} {{ $user->name }} {{ $user->email }}
#endforeach
Change VIEW-NAME-HERE with the name of your view file, for example index or users.index
You Are using php in blade file
first make controller
for controller run a command in terminal
php artisan make:controller usercontroller
then write this:
class usercontroller extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
$data = compact('users')
return view('your-view-name')->with('$data');
}
}

Passing input (form) from a page to itself

I am working on my first laravel script, trying to submit a form and see the input on the same page. I am working on this problem for days, hopefully someone can solve this. The problem is that i get this error:
Undefined variable: data (View: D:\Programmer\wamp\www\laravel\app\views\bassengweb.blade.php)
view: Bassengweb.blade.index
#extends('master')
#section('container')
<h1>BassengWeb testrun</h1>
<table>
{{ Form::open(array('route' => 'bassengweb', 'url' => '/', 'method' => 'post')) }}
<tr>
<td>{{ Form::label('bassengId', 'Basseng ID')}}</td>
<td>{{ Form::text('bassengId') }}</td>
</tr>
<tr>
<td>{{ Form::label('frittKlor', 'Fritt Klor')}}</td>
<td>{{ Form::text('frittKlor') }}</td>
</tr>
<tr>
<td>{{ Form::label('bundetKlor', 'Bundet Klor')}}</td>
<td>{{ Form::text('bundetKlor') }}</td>
</tr>
<tr>
<td>{{ Form::label('totalKlor', 'Total Klor')}}</td>
<td>{{ Form::text('totalKlor') }}</td>
</tr>
<tr>
<td>{{ Form::label('ph', 'PH')}}</td>
<td>{{ Form::text('ph') }}</td>
</tr>
<tr>
<td>{{ Form::label('autoPh', 'Auto PH')}}</td>
<td>{{ Form::text('autoPh') }}</td>
</tr>
<tr>
<td>{{ Form::submit('Lagre målinger') }}</td>
{{ Form::close() }}
</table>
#if($data)
{{ $data->bassengId }}
#endif
#stop
Homecontroller.php
<?php
class HomeController extends BaseController {
public function showWelcome()
{
return View::make('hello');
}
public function showTest()
{
return View::make('test');
}
public function getInput()
{
$input = Input::all();
print_r($input); die();
return View::make('bassengweb')->with('data', '$input');
}
}
view: master.blade.php
<div class="container">
#yield('container')
</div>
routes.php
Route::get('/', function()
{
return View::make('bassengweb');
});
//Route::post('/', array('uses'=>'HomeController#getInput'));
Route::post('/',function(){
$input = Input::all();
//for inspecting input
print_r($input);
die();
//to send input to view but before sending to view comment last two lines
return View::make('bassengweb')->with('data',$input);
You enclosed $input in single quotes in your HomeController.php, instead try:
<?php
class HomeController extends BaseController {
public function showWelcome()
{
return View::make('hello');
}
public function showTest()
{
return View::make('test');
}
public function getInput()
{
$input = Input::all();
print_r($input); die();
return View::make('bassengweb')->with('data', $input);
}
}
In your routes.php, change route registration a little.
Route::get('/', function()
{
$data = Input::all();
return View::make('bassengweb', compact('data'));
});

Categories