laravel model controller retrieve data - laravel

I'am new to laravel and had a hard time for eloquent ORM, I like to retrieve Favourite items from the table with specific user id, but seem I don't find a way to display the data correctly.
I refer and copied the favourite model code from here
Model: Favourite
class Favourite extends BaseModel
{
public function favouritable()
{
return $this->morphTo();
}
}
Model: Course
public function favourites()
{
return $this->morphMany(Favourite::class, 'favouritable');
}
public function myFavourite()
{
return $this->favourites()->where('favor_user', '=', auth()->user()->id);
}
Controller: FavouriteController#index
public function index()
{
$course = new Course();
$myfavs = $course->myFavourite();
//dd($myfavs);
$this->vdata(compact('myfavs'));
return view('front.favorites', $this->vdata);
}
In blade view, but return empty/blank data:
#foreach($myfavs as $myfav)
{{ $myfav->$course_name }}
#endforeach
When i dd($myfavs) it display pretty bunches of data that i couldn't find the data that is stored in the favourites table.

I think you have added the conditions but forgot get the results with one of the methods to do so.
Try :
$myfavs = $course->myFavourite()->get();
Or :
$myfavs = $course->myFavourite()->take(<N>)->get;
Or
::all()
etc. take a look at : https://laravel.com/docs/5.8/eloquent#retrieving-models

Related

Laravel - Return related models of parameter in controller

I have the following route:
Route::get('/api/products/{product}', 'ProductController#get');
My Product model looks like this:
class Product extends Model
{
public function ingredients()
{
return $this->belongsToMany(Ingredient::class)->withPivot('value');
}
}
In my controller, the method is:
public function get(Product $product)
{
return $product;
}
This only returns the attributes of the Product object as a JSON. I would also like to return the related ingredients and pivot table values (as it would with the with method), and possibly other related models.
return $product->with('ingredients') creates a collection of all Products, so that doesn't really work, I have to filter it again by the product ID. I can obviously construct the JSON myself, but that becomes tedious if I want multiple related models included. Is there an easy way to accomplish this?
You have three options:
Using $with in model
class Product extends Model
{
protected $with = ['ingredients'];
public function ingredients()
{
return $this->belongsToMany(Ingredient::class)->withPivot('value');
}
}
Load the relation and return product:
public function get(Product $product)
{
$product->ingredients;
return $product;
}
Use the load method on the product:
public function get(Product $product)
{
return $product->load('ingredients');
}

Qyerying a one-to-many relationship

So I have tables Uploads and Avtors (Authors). I am trying to write a query that will get me all the uploads for a given user + the author.
To achieve this I have the following function in my controller :
public function uploads()
$uploads = Auth::user()->upload()->with('author')->paginate(10);
return view('uploads')->with('uploads',$uploads);
}
This function manages to get me all the uploads for a given user, but not the author :
When I debug with dd I get this :
My relationships in the models are difined in the following ways :
User:
public function upload(){
return $this->hasMany('App\Upload');
}
Avtor:
class Avtor extends Model
{
public function uploads(){
return $this->hasMany('App\Upload');
}
}
Upload:
public function user(){
return $this->belongsTo('App\User');
}
public function author(){
return $this->belongsTo('App\Avtor');
}
Can anybody help me find out what am I doing wrong here because I can't by myself?
You can use load() method with nested relationship dot syntax:
auht()->user()->load(['uploads', 'uploads.author'])->get();
In this case, you'll not need to pass any data to a view, just do this:
#foreach (auth()->user()->uploads as $upload)
Or you can use with() method:
$uploads = Upload::with('author')->where('user_id', auth()->id())->get();

Laravel Relationship not working on server

My project is working fine on local host, but on the server, getting error only on lesson page.
Subject Model is
class Subjects extends Model
{
public function category()
{
return $this->belongsTo('Lea\Category');
}
public function lesson()
{
return $this->hasMany('Lea\Lessons');
}
public function chapter()
{
return $this->hasMany('Lea\Chapters');
}
public function users()
{
return $this->belongsToMany('Lea\User', 'subject_user', 'subject_id', 'user_id');
}
}
And Lesson Model is
class Lessons extends Model
{
public function chapter()
{
return $this->belongsTo('Lea\Chapters');
}
public function subject()
{
return $this->belongsTo('Lea\Subjects', 'subject_id');
}
public function category()
{
return $this->belongsTo('Lea\Category');
}
}
My controller lessons has method index like below.
public function index()
{
$lessons = lessons::orderBy('id', 'asc')->paginate(5);
return view('admin.lessons.index')->withLessons($lessons);
}
The way i am calling subject name is show below. first subject is relationship subject and 2nd subject is the field name where subject name saved in db. using foreach to get data like:
#foreach ($lessons as $lesson)
{{$lesson->subject->subject}}
#endforeach
subjects table schema is
id
subject
admin_id
users_id
category_id
created_at
updated_at
lessons table schema is
id
title
slug
category_id
subject_id
chapter_id
users_id
content
image
That's more like it ;)
Just edit how you are passing the object to the following:
...
return view('admin.lessons.index')->with(compact('lessons'));
What this is doing:
compact() essentially takes the object/variable by it's name ($lessons) and passes it to the view with the same name.
An alternative way is to write it as:
...
return view('admin.lessons.index')->with('lessons', $lessons);
Cheers!
The reason you're getting the error in your server but not your local machine is that your server database is empty (or at least has fewer records).
{{$lesson->subject->subject}}
The lesson has no subject, so it's null. And your tryting to get a proprty subject of a null.
If you're using Laravel 5.5, you can wrap the subject in optional() method.
{{optional($lesson->subject)->subject}}
< Laravel 5.5
{{$lesson->subject ? $lesson->subject->subject : ''}}

Defining relationship on pivot table elements in laravel

I'm building a small application on laravel 5.4 where I'm having following models and relationship:
Interaction Model:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')->withPivot('company_id')->withTimestamps();
}
Contact Model:
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')->withTimestamps();
}
and Company Model:
public function contacts()
{
return $this->belongsToMany('App\Contact', 'company_contact', 'company_id','contact_id');
}
Now I'm fetching some data something like this:
$tempData['contacts'] = $interaction->contactsAssociation()->with('company')->get();
I want to extract company data from the pivot table which is mentioned in the relationship. Currently I can't find solution so I have to do:
$tempData['contacts'] = $interaction->contactsAssociation()->get();
$companies = [];
foreach($tempData['contacts'] as $contact)
{
$companies[] = Company::find($contact->pivot->company_id);
}
$tempData['company'] = $companies;
Guide me on this, thanks,
You can pass an array to the withPivot() function with every field you want to retrieve:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')
->withPivot(['company_id', 'other_field'])
->withTimestamps();
}
Hope this helps you.

Laravel 4.1: proper way to retrieve all morphedBy relations?

Just migrated to 4.1 to take advantage of this powerful feature.
everything seems to work correctly when retrieving individual 'morphedByXxxx' relations, however when trying to retrieve all models that a particular tag belongs to -- i get an error or no results.
$tag = Tag::find(45); //Tag model name = 'awesome'
//returns an Illuminate\Database\Eloquent\Collection of zero length
$tag->taggable;
//returns Illuminate\Database\Eloquent\Relations\MorphToMany Builder class
$tag->taggable();
//returns a populated Collection of Video models
$tag->videos()->get();
//returns a populated Collection of Post models
$tag->posts()->get();
My Tag Model class loooks like this:
class Tag extends Eloquent
{
protected $table = 'tags';
public $timestamps = true;
public function taggable()
{
//none of these seem to function as expected,
//both return an instance of MorphToMany
//return $this->morphedByMany('Tag', 'taggable');
return $this->morphToMany('Tag', 'taggable');
//this throws an error about missing argument 1
//return $this->morphToMany();
}
public function posts()
{
return $this->morphedByMany('Post', 'taggable');
}
public function videos()
{
return $this->morphedByMany('Video', 'taggable');
}
}
And the Post and Video models look like this:
class Post extends Eloquent
{
protected $table = 'posts';
public $timestamps = true;
public function tags()
{
return $this->morphToMany('Tag', 'taggable');
}
}
I am able to add/remove Tags to Posts and Videos as well as retrieve the related Posts, and Videos for any Tag -- however -- what is the proper way to retrieve all Models having the Tag name 'awesome'?
Was able to figure it out, would love to hear comments on this implementation.
in Tag.php
public function taggable()
{
return $this->morphToMany('Tag', 'taggable', 'taggables', 'tag_id')->orWhereRaw('taggables.taggable_type IS NOT NULL');
}
in calling code:
$allItemsHavingThisTag = $tag->taggable()
->with('videos')
->with('posts')
->get();
I just used this on Laravel 5.2 (not sure if it is a good strategy though):
Tag model:
public function related()
{
return $this->hasMany(Taggable::class, 'tag_id');
}
Taggable model:
public function model()
{
return $this->belongsTo( $this->taggable_type, 'taggable_id');
}
To retrieve all the inverse relations (all the entities attached to the requested tag):
#foreach ($tag->related as $related)
{{ $related->model }}
#endforeach
... sadly this technique doesn't offer eager load functionalities and feels like a hack. At least it makes it simple to check the related model class and show the desired model attributes without much fear to look for the right attributes on the right model.
I posted a similar question in this other thread as I am looking for relations not known in advance.

Resources