Blank Page Laravel: 50k+ table entries - php

I'm trying to display data obtained from a database on a simple html page. The code works fine with smaller entries. When i query a larger database (50k+ entries), it returns a blank page. So i am of the assumption that the size of the table is the issue here, i do not recieve any error reports whatsoever. Can someone take a look at my code and advice on how i can deal with this?
Model:
<?php
//Model (file name: Completion)
class Completion extends Eloquent{
protected $table = 'completion_date';
public $timestamps = false;
}
Controller:
class CompletionController extends BaseController {
public function index() {
$lsz = Completion::all();
return View::make('completion.lsz', ['completion' => $lsz]);
}
}
Route:
Route::get('/Completion', 'CompletionController#index');

Go to app/config/app.php and set debug to true. Try to use paginate for split your database queries.
$lsz = Completion::paginate(100);

Related

Eloquent relationship only returns result for first result in array

I have the following model with these relationsships:
class Site extends Model
{
use HasFactory;
public function tests() {
return $this->hasMany(Test::class,'requestedUrl','frontpage');
}
public function latestTests() {
return $this->tests()->latest()->take(1);
}
}
I have the following eloquent statement:
$sites = Site::
->with('latestTest')
->orderBy($sort, $direction)
->paginate($size);
But in the result it is only the first returned record that contains latestTest. I assume it's because of take(1) but if I remove that I will choke the server since it seems to be fetching all the tests (100k+ rows) before servering the latest (at least that is what I can see in my queries log).
So how do I get the latest test "the right way"?

Laravel Call to a member function first() on null

I'm using VueJS and Laravel for an application I'm developing. I've tried to search here for an answer, but I haven't found anything that works. Most of the times, it's because there's really nothing to return, but I've tried to debug my query quite a bit, and I don't understand why I keep getting a null.
So I'm trying to get information about the student who's logged in, so I'm doing an axios get on a route that executes the following:
public function getByUserId($id) {
//$student = $this->studentRepo->findByUserId($id);
$student = Student::where('user_id', $id)->first();
$inscription = Inscription::where('student_id', $student->id)->first();
$student->careers;
$res = $inscription ? new InscriptionResource($inscription) : '';
return response()->json([
'student' => new StudentResource($student),
'inscription' => $res,
]);
}
The thing is, it doesn't find the student with that user_id. I've checked if the user_id (param: $id) is getting there as expected and it is. I've also tried to get the query via ->toSql() and copy pasted the query on the database to test it and I do get the student I'm trying to search for. Thing is, it's not finding it in Laravel for some reason, I'm not sure why.
My student table does have the attribute "user_id", I've checked.
Student file:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Student extends Model {
use SoftDeletes;
protected $dates = ['deleted_at'];
public function charges() {
return $this->hasMany('App\Models\Payment');
}
}
Add the related column in the relation function
public function charges() {
return $this->hasMany('App\Models\Payment', '');
}

Filter results in has many relationship

I'm struggling to filter some results.. I have a table called "Process", and another called "Actors". Process has many Actors. Here's the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Process extends Model
{
public function actors()
{
return $this->hasMany(Actor::class)->orderBy('actor');
}
}
So I have a view where I show all process and their actors. The thing is, I want to make an option to filter, where I would check if the Auth::user()->username is the same as Actor->actor.
I tried something along the lines of:
public function index()
{
$processes = Process::all();
$processes ->actors()->where('actor', 'Test')->get();
return view('process.process', compact('processes '));
}
(In the Where I compare to Test for testing purposes, if I did get it to work I would change it to Auth::user()->username obviously)
This shows the following error:
BadMethodCallException Method
Illuminate\Database\Eloquent\Collection::actors does not exist.
I've tried some variations(running a foreach in the controller for example, but either I did it wrong or thats not the way to do it...) but to no avail. Any help is greatly apreciated!
I assume that you want to grab all processes of the current authenticated user if yes this is what you need.
public function index()
{
$processes = Process::whereHas('actors',function($query){
$query->where('id',Auth::user()->id);
});
return view('process.process', compact('processes '));
}

laravel eloquent orm view

My ultimate goal is to print the contents of a table in a database to a table in HTML using Laravel's ORM.
Beyond that I know how to configure the database file, but is there any other things i need to configure.
From my understanding I need three files. Do i need to make a controller? If so how does that work?
Item Class
Route.php
views.php
Here is what I have so far
Item.php
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model {
protected $table = 'items';
protected $primaryKey = 'item_id';
public function products()
{
return $this->belongsTo('item_id', 'item_name', 'item_cost');
}
}
routes.php
<?php
Route::get('Product', function()
{
$products = \App\items::all();
return view('Items', $items);
});
and I have no idea how to create a view in HTML.
I know I'm completely off at this point, but I've read the documentation and I am still completely lost when they reference things like URI and have URL in the same sentence without defining or even linking to it elsewhere in the documentation.
Actually, you have declared your Eloquent ORM like this:
class Item extends Model {
// ...
}
But you are using that model/class like this:
$products = \App\items::all();
In this case, \App\items doesn't exist, it should be:
$items = \App\Item::all(); // <-- Item not items
return view('items', $items); // <-- $items not $products
You asked: Do i need to make a controller?
In this case, no, it'll work fine with the anonymous function but using a Controller is better for many reasons.
Update:
Create a view in resources/views as items.blade.php and you can print out the items through a foreach loop. Check the documentation.

Laravel Eloquent::Find() returning NULL with an existing ID

It's pretty straightforward as it's the most basic thing but I don't know what I'm missing:
Having a model called Site
I'm using Eloquent ORM, so when I call (in a controller)
$oSite = Site::find(1)
and then
var_dump($oSite);
It returns a value of NULL.
But when I check the database, the table 'sites' actually contains the following item:
id: 1
user_id: 1
name: test
In my Site model I have the following code:
use Illuminate\Database\Eloquent\ModelNotFoundException;
Class Site extends Eloquent {
protected $table = 'sites';
protected $fillable = ['user_id', 'name'];
}
Instead, if I gather the item with the following:
$oSite = DB::table('sites')
->where('id', 1)
->first();
It works and I get the correct register.
What I'm doing wrong? Which part of the documentation I didn't get?
EDIT:
Model code can be checked above.
Controller:
use Illuminate\Support\Facades\Redirect;
class SiteManagementController extends BaseController {
...
public function deleteSite()
{
if (Request::ajax())
{
$iSiteToDelete = Input::get('siteId');
$oSite = Site::find($iSiteToDelete);
return var_dump($oSite);
}
else
{
return false;
}
}
}
EDIT 2: (SOLVED)
Real reason why wasn't working:
I had originally in my model code the following:
use Illuminate\Database\Eloquent\SoftDeletingTrait;
use Illuminate\Database\Eloquent\ModelNotFoundException;
Class Site extends Eloquent {
protected $table = 'sites';
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
protected $fillable = ['user_id', 'name'];
}
Problem was I added a 'deleted_at' column after I started the project and when I applied migrations, I didn't have softdeleting enabled.
Obviously, I did a second error, forgetting to enable 'deleted_at' to be nullable, hence all inserts went had a wrong timestamp (0000-00-00 ...).
Fix:
Made nullable 'deleted_at' column.
Set all wrong 'deleted_at' timestamps to NULL.
Check you are getting Input::get('siteId') correctly. if you are getting it then try to convert it into integer i.e
$iSiteToDelete = intval(Input::get('siteId'));
You're not returning your model.
var_dump prints output and returns nothing.
do this instead:
dd($oSite); // stands for var_dump and die - a helper method
and even better, simply return the model:
return $oSite; // will be cast to JSON string
In my case I was using a custom query with the DB facade. I neglected to skip records that have a deleted_at in my DB query. When showing all the records, it worked with IDs that had already been deleted, so methods like find that if they were considering the deleted_at, did not find the record.
Layer eight.
For the future if you encounter a similar problem you can check what SQL queries laravel is sending to the database.
Todo so just enable query logging by using DB facade:
\DB::enableQueryLog();
Before sending request to database.
Then after using find() or get() you can get all requests by:
\DB::getQueryLog();
You can getQueryLog into dd() function and see what database queries were made.

Categories