Laravel - virtual column id -> uuid - laravel

I have two models:
Ingredient, Category
Each ingredient has a category id, each category has many ingredients.
The problem is that I use auto-increment ids for joins and queries internally, but only show UUIDs to end users.
So the Ingredient table looks like this:
id uuid name category_id
And the category table looks like this:
id uuid name
My data in ingredients looks like this:
id: 1,uuid:{a uuid}, name: Ingredient A, category_id: 1
When I do a Ingredient::get(), I want to return this:
uuid: {ingredient uuid}, name: Ingredient A, category_uuid: {the category uuid}
Based on what I am learning about Laravel, you can use accessors and mutators.
I set up
protected $appends = [
'category_uuid'
];
and
public function category()
{
return $this->belongsTo(Category::class);
}
public function getCategoryUuidAttribute()
{
return $this->category()->uuid;
}
But I get this error:
message: "Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$uuid"
What am I doing wrong?

It seems the issue was adding ->first() to the method chain, and that handled it.
So it becomes:
public function getCategoryUuidAttribute()
{
return $this->category()->first()->uuid;
}

You can also achieve this using Query Builder:
public function index()
{
$ingredients = DB::table('ingredients')
->join('categories', 'ingredients.category_id', 'categories.id')
->select('ingredients.*', 'categories.uuid as c_uuid')
->get();
return view('index', compact('ingredients'));
}
#foreach($ingredients as $ingredient)
<ul>
<li>{{ $ingredient->uuid }}</li>
<li>{{ $ingredient->name }}</li>
<li>{{ $ingredient->c_uuid }}</li>
</ul>
#endforeach

Related

Laravel Eloquent "With" and sub "With" relationship query -> pass Column Value as Where clause

I have 3 Models "Category" (tableName = 'categories'), "Brand" ('brands'), "Item" ('items')
Can I pass parent column value (e.g. categories) to use it in the Where clause?
Simple example:
Category::with(['brands' => function ($q) {
$q->with(['items' => function ($query) use ($localWhereHas) {
$query->whereColumn('category_id', 'categories.id');
}]);
}]);
Relations are:
Category Model:
public function brands(): BelongsToMany
{
return $this->belongsToMany(Brand::class, 'category_brands')->withPivot('is_visible', 'addon_price');
}
Brand Model:
public function items(): HasMany
{
return $this->hasMany(Item::class, 'brand_id');
}
Item Model:
public function category(): BelongsTo
{
return $this->belongsTo(Category::class, "category_id");
}
The main idea is that I need the structure to be nested like this Category->Brands->Items
The backup plan is to fetch All needed Categories and Foreach them to get as many as categories I have all Brands->Items, using categoryId ($category->category_id) .... but I don't like it
No, you can't pass it directly because it is not the same context.
If you want to have a display like this :
Category
-brand
-item
Then you should maybe just group your items by brand :
$categories = Category::with('items.brand')->get();
#foreach($categories as $category)
{{ $category->name}}
#foreach($category->items->groupBy('brand_id') as $brand_id => $items)
{{ $items->first()->brand->name }}
#foreach($items as $item)
{{ $item->name }}
#endforeach
#endforeach
#endforeach

Building complex Eloquent query using belongsToMany relationship, foreign table and whereIn()

In a Laravel 5 app, I have 5 tables - users, books, authors, followers and activity_feeds.
Users can follow authors and a book can have several authors.
When a book is made, an activity_feeds entry is made that references the book_id.
I need to build an eloquent query to get a collection of activity_feeds for each users, to iterate over in their home page activity feed.
My Book model includes
public function authors()
{
return $this->belongsToMany('App\Author')->withTimestamps();
}
The activity_stream table looks like this (with example data)
id (1)
user_id (3)
type (New Book)
book_id (18)
created_at etc
and my User controller includes
public function feedItems()
{
return $this->hasMany('App\ActivityFeed');
}
public function userFollowings()
{
return $this->belongsToMany('App\User', 'followers', 'follower_id', 'subject_id')->withTimestamps();
}
public function authorFollowings()
{
return $this->belongsToMany('App\Author', 'followers', 'follower_id', 'author_id')->withTimestamps();
}
My current query (which isn't working), contained in the User model is
public function getactivityFeedsAttribute()
{
$userFollowings = $this->userFollowings()->pluck('subject_id')->toArray();
$authorFollowings = $this->authorFollowings()->pluck('author_id')->toArray();
$userFeeds = ActivityFeed::whereIn('user_id', $userFollowings)
->orwhereIn('book_id', function($query){
$query->select('id')
->from(with(new Book)->getTable())
->whereHas->authors()
->whereIn('id', $authorFollowings);
})
->get();
return $userFeeds;
}
$userFollowings and $authorFollowings are working fine.
I'm not sure I'm using the correct syntax for data[book_id] to pluck the book id from the activity_feeds row, and I'm really not sure if I can nest a table look up or use $query like this.
It also seems VERY complicated. Am I might be missing something much more straight forward?
In the blade I am calling like this
#forelse ($user->activityFeeds as $activityFeed)
<div class="row">
<div class="col-2">
{{ $activityFeed->user->firstname }}
</div>
<div class="col-2">
{{ $activityFeed->type }}
</div>
</div>
<hr>
#empty
No activity yet
#endforelse
Which works if I just query 'ActivityFeed::whereIn('user_id', $userFollowings)'
I'll rewrite the query in an answer because comments aren't very legible.
public function getactivityFeedsAttribute()
{
$userFollowings = $this->userFollowings()->pluck('subject_id')->toArray();
$authorFollowings = $this->authorFollowings()->pluck('author_id')->toArray();
$books = Book::whereHas('authors', function ($query) use ($authorFollowings) {
// Have to be explicit about which id we're talking about
// or else it's gonna throw an error because it's ambiguous
$query->whereIn('authors.id', $authorFollowings);
})->pluck('id')->toArray();
$userFeeds = ActivityFeed::whereIn('user_id', $userFollowings)
->orwhereIn('book_id', $books)
->get();
return $userFeeds;
}

accessing collections within collections laravel 5

I have a table of "rosters" that's pretty much strictly foreign keys. It acceses the "schools" table, "courses" table, and "students" table. So essentially, a 'student' takes a 'course' at a 'school'. My RostersController has this
public function show($id)
{
$roster = Roster::where('course_id', $id);
return view('roster')->with('roster', $roster);
}
My Roster Model is:
public function students()
{
return $this->hasMany('App\Student');
}
My student Model is:
public function roster()
{
return $this->belongsTo('App\Roster');
}
my view is this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>{{$child->students->first_name}}</p>
#endforeach
The rosters table just saves the student_id rather than all of the student's data that is already in the 'students' table. So i'm trying to access the students table from this relation but when i run this, it tells me that anything related to the students table is 'not on this collection'. I know that I could do things this way if i was working with a hasOne relationship, but how can i accomplish this with a hasMany to output the students table value in each row?
You should try this
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id);
return view('roster')->with('roster', $roster);
}
Try this
Roster.php
public function show($id)
{
$roster = Roster::with('students')->where('course_id', $id)->get(); // load the students
return view('roster')->with('roster', $roster);
}
On the view
#foreach ($roster as $child)
<p>{{$child->id}}</p>
<p>
<!-- Loop through the stundents since this returns an collection of students and not just one -->
#foreach($child->students as $student)
{{$student->first_name}} <br>
#endforeach
</p>
#endforeach
Check this for more information on eager loading
The $child->students is a collection. So, you need to use another foreach loop inside the first one.
Your code should look like this:
#foreach ($roster as $child)
<p>{{$child->id}}</p>
#foreach($child->students as $student)
<p>{{$student->first_name}}</p>
<p>{{$student->age}}</p>
<p>{{$sutdent->another_column_in_students_table}}</p>
#endforeach
<p>{{$child->any_other_column_in_roster_table_if_needed}}</p>
#endforeach
So, your first issue is, that
$roster = Roster::where('course_id', $id);
will just return a QueryBuilder instance, you have to use
$roster = Roster::where('course_id', $id)->get();
then for sure, students is a collection, you have to iterate over it like this:
#foreach ($child->students as $student)
{{ $student->yourProperty}} <br>
#endforeach
Update:
I saw you know already about that when to use get() in query laravel 5

How to count how many articles belongs which category?

I have this relationships:
ARTICLES
public function category()
{
return $this->belongsTo('App\Models\Categories');
}
CATEGORY have translations
public function c_translations()
{
return $this->hasMany('App\Models\CategoryTranslations', 'category_id');
}
In articles i have category id, also in translations i have category_id. So how can i count how many articles have each category. Any suggestion?
$articles = Articles::all();
foreach($articles as $article ){
$articles_category = Articles::where('id',$article->id)->withCount('category')->first();
}
I tried this but always get 0 for all of categories
Define a hasMany relation in your Category model as:
public function articles()
{
return $this->hasMany('App\Models\Article');
}
Then you can use withCount to query it as:
$categories = Category::withCount('articles')->get();
Pass it to your view and then you can access the no. of articles of category as:
#foreach ($categories as $category)
<li>{{ category->title }}</li>
<li>{{ category->articles_count }}</li>
#endforeach
Use withCount() method to count relation.
Model::where('id', $id)->withCount('relation')->first();
If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models.
I think you should use a group by statement.
You select category_id,COUNT(*) FROM articles GROUP BY category_id
This will return the number of articles for each category_id

How to safely access other users and other model's records inside Blade template

I have 3 models in my app Users, Sales and Plans, when I render sales for each customer (due to storing) I only get id's for other users and models related to that sale (like account manager, owner, plan), now I'm trying to use those ID's inside blade to get names or other rows based on ID and model. Here is the show function:
public function show($id) {
$user = User::find($id);
$sales = Sale::where('customer_id', '=', $id)->get();
return view('profiles.customer', ['user' => $user, 'sales' => $sales]);
}
And in blade I get all those sales like:
#foreach ($sales as $sale)
<li>
<i class="fa fa-home bg-blue"></i>
<div class="timeline-item">
<span class="time"><i class="fa fa-clock-o"></i> {{$sale->created_at->format('g:ia, M jS Y')}}</span>
<h3 class="timeline-header">{{$user->name}} became a customer</h3>
<div class="timeline-body">
<p>Date: {{$sale->sold_date}}</p>
<p>Price: {{$sale->sale_price}}</p>
</div>
</div>
</li>
#endforeach
So inside each record I have like "account_manager_id", "agent_id", "owner_id", "plan_id".
Currently I have this solved by adding public static function (this is for users, have same function for Plan model as well) in Sale model class:
public static function getUser($id) {
return User::where('id', $id)->first();
}
And I'm using it like this in Blade:
Account manager: {{$sale->getUser($sale->account_mgr_id)->name}}
Is this the safest and best way to do it? Or there is something I'm overlooking here?
You need to add relationships in your Sales Model.
class Sales extends Eloquent {
.....
.....
public function accountManager() {
return $this->hasMany('App\User', 'account_manager_id');
}
public function agents() {
return $this->hasMany('App\User', 'agent_id');
}
public function owner() {
return $this->hasOne('App\User', 'owner_id');
}
}
Now $sales->agents will give you a user with agent_id as id in User table.
Update your hasOne, hasMany relationships as your need. Laravel Documentation.
From your blade template, your access your AccountManager as
#foreach($sales->accountManager as $manager)
Name: {{ $manager->name}}
#endforeach
I think you could use Eloquent relationships. Taking your example, you should define relationship in your User model:
<?php
class User extends Eloquent {
public function sales() {
return $this->hasMany(Sale::class, 'customer_id');
}
}
Then, whenever you need to get sales of that user (entries, that relate via customer_id column), just simply do
<?php
$user = User::find($id);
$sales = $user->sales;
This is very fun when when you have to print out list of users that have sales, for example
<?php
public function showUsersWithSales() {
$users = User::with('sales')->get();
return view('users-with-sales', compact('users'));
}
users-with-sales.blade.php example:
#foreach ($users as $user)
User: {{ $user->name }}<br>
Sales:<br>
#foreach ($user->sales as $sale)
{{ $sale->amount }} {{ $sale->currency }} # {{ $sale->created_at }}<br>
#endforeach
<hr>
#endforeach
It would print all users with their sale amount and currency, followed by date when it was created.
This sample takes into account, that your User model has name attribute and your Sale model has amount, currency, created_at and customer_id fields in your database.
To reverse the action, say you have a sale and want to know who made it, just simply define a relationship!
<?php
class Sale extends Eloquent {
public function customer() {
return $this->belongsTo(User::class, 'customer_id');
}
}
Hope that helps!
Eloquent Relationship is your friend, https://laravel.com/docs/5.2/eloquent-relationships and you can solve your problem easily.
Suggestion is to remove all those function access and control from view and put it somewhere else. This will be good habit for you so you can avoid the infamous fat view.

Resources