Filter results in has many relationship - php

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 '));
}

Related

Laravel - 404 | Not Found upon "/{id}" entry

I am getting a "404 | Not Found" error when i try to access a specific item from my database. The items with the specific ID's do exist in the database, but i am not even sure if that even has any influence on the problem.
My routing looks likes this:
Route::prefix('departments')->group(function() {
Route::get('/{id}', [DepartmentController::class, 'showDepartment']);
});
And the related controller looks like this:
public function showDepartment() {
return '';
}
}
I haven't yet finished the function. I just wanted to check if the routing even worked by returning an empty string.
So what am i doing wrong? Is it the routing or the controller?
According to the Laravel documentation, you have to define the parameter in the route then use it in the controller as a parameter.
in your controller:
public function showDepartment($id) {
return 'Hello';
}
The id is not bound to any model to fetch from the database to do that you can use Laravel route model binding
for example when you have a model named Department you write your route like this:
Route::get('/{department}', [DepartmentController::class, 'showDepartment']);
and in the controller:
public function showDepartment(Department $department) {
return 'Hello from depratment';
}
When your department exists it returns the response otherwise return 404.
You may need a Department model class. Then you can find the item from database by id $department = Department::findOrFail($id);
you are send parameter in route and this function without any parameter
route :
Route::prefix('departments')->group(function() {
Route::get('/{id}', [DepartmentController::class, 'showDepartment']);
});
your function in controller should be
public function showDepartment($id) {
$department = Department::findOrFail($id);
}
}

How to Laravel relationship(hasMany) use limit or take for each records with pagination

I have comment List API with Pagination in laravel and I want a comment replay Array with every comment but only the last 3 comment replay.
public function CommentReplay(){
return $this->hasMany('App\PostCommentReplies','comment_id','id')->orderBy('id','DESC');
}
And Query I have use
PostComments::select('post_comments.*')->with(['users','CommentReplay'=> function ($query) {
$query->select('post_comment_replies.*')
->orderBy('id','DESC')->take(3);
}])->orderBy('id','DESC')->paginate(10);
In this, I have been getting only the last 3 comments of all CommentReplay arrays. I have been not getting each comment's last 3 replies. I want each comment's to last 3 replies.
Anyone can help me on it.
Thank you!
you can use the trait: HasEagerLimit:
you can install it:
composer require staudenmeir/eloquent-eager-limit:"^1.0"
and then in your model:
class PostComments extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
public function CommentReplay(){
return $this->hasMany('App\CommentReplay');
}
public function limitCommentReplay(){
return $this->hasMany('App\CommentReplay')->latest()->limit(3);
}
}
and also in PostCommentReplies model:
class CommentReplay extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
now : when you load your relation ... it should return the result you desire:
PostComments::select('post_comments.*')->with(['users','limitCommentReplay'])->orderBy('id','DESC')->paginate(10);

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', '');
}

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.

Blank Page Laravel: 50k+ table entries

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);

Categories