when try to get all comment for one Article by Article::first() but first()
Bring just the first article
i try use find() like
$comments = Article::find()-> commentsArticle()->with('articles');
return Datatables::of($comments)
i get error so how i can Pass a value to view all comments for one article
or
my be there is way without using find()
Article model
class Article extends Model{
public $table = 'articles';
public function commentsArticle() {
return $this->hasMany('App\Comment');
}
}
controller
enter code here
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Yajra\Datatables\Datatables;
use App\Article;
use App\Comment;
class CommentController extends Controller{
public function commentsForOne Article()
{
$comments = Article::all()->commentsArticle->with('articles');
return Datatables::of($comments)->make(true);
}
}
last error i get
ErrorException (E_DEPRECATED)
Non-static method Yajra\Datatables\Datatables::collection() should
not be called statically
I hope find any idea or example like that will help me to learn
You are trying to get the first articles with its comments.
public function commentsForOneArticle($id)
{
$article = Article::fine($id);
//check if article exists to avoid errors
if ( $article ) {
return Datatables::of(Comment::where('article_id', $article->id))->make(true);
}
return "no article with id" . $id;
}
This was just an illustration. But it seems you need to understand first how Eloquent works. Watch this free Laracast https://laracasts.com/series/laravel-from-scratch-2017/episodes/7
For routes, you can define the route like this:
Route::get('comments/{article_id}', 'ArticleController#commentsForOneArticle');
And call it in Ajax like
$.ajax({url: "/comments/1",
success: function(result){
//do stuff here
},
error: function(error) {
console.log(error)
}
});
All this is just a guide and not THE solution.
Edit
To take data with the user in one go
$article = Article::with('user')->find($id);
//will include all the fields from user and article
Comments & author
To get the name of the comment author, you need to define the relationship in comment model
public function user() {
return $this->belongsTo(User::class);
}
Then get like this
if ( $article ) {
return Datatables::of(Comment::with('users')->where('article_id', $article->id))->make(true);
}
Related
in Course model this relation are include
public function course_modules()
{
return $this->hasMany(CourseModule::class, 'course_id');
}
public function course_lessons()
{
return $this->hasMany(CourseLesson::class, 'course_id');
}
public function course_contents()
{
return $this->hasMany(CourseContent::class, 'course_id');
}
i want to make a array for hasMany relation like
$hasMany=[
CourseModule::class,
CourseLesson::class
]
I wanted to do this for fun, turned out pretty difficult, but here you go, there are some requirements you need to make sure of, but it gets the job done, I will be using a mix of PHP & Laravel to accomplish this.
Step 1: Make sure your main class has proper return method types. So in your case.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Course extends Model
{
public function course_modules() : HasMany
{
return $this->hasMany(CourseModule::class, 'course_id');
}
public function course_lessons() : HasMany
{
return $this->hasMany(CourseLesson::class, 'course_id');
}
public function course_contents() : HasMany
{
return $this->hasMany(CourseContent::class, 'course_id');
}
}
Step 2: In your controller, you need to use ReflectionClass, would love if someone actually can improve this for learning purposes.
<?php
namespace App\Http\Controllers;
use ReflectionClass;
class CourseController extends Controller
{
public function test(){
//We will build a hasMany array
$hasMany = [];
//here we will use ReflectionClass on our primary class that we want to use.
$reflection = new ReflectionClass(new \App\Models\Course);
//Lets loop thru the methods available (300+ i don't like this part)
foreach($reflection->getMethods() as $method){
//if the method return type is HasMany
if($method->getReturnType() != null && $method->getReturnType()->getName() == 'Illuminate\Database\Eloquent\Relations\HasMany'){
//we grab the method name
$methodName = $method->getName();
//then we finally check for the relatedClass name and add to the array
array_push($hasMany, get_class(($instance = new Course)->$methodName()->getRelated()));
}
}
//lets dump to see the results
dd($hasMany);
}
Results: an array of the classes :D
array:2 [▼
0 => "App\Models\ProgramTest",
1 => "App\Models\ProgramAnotherTest"
]
According to syntax, we are not able do this in Laravel. However, you can use an model mutors to solve this issue.
public function getCourseDetailsAttribute(){
$arr=[
"course_modules"=>$this->course_modules(),
"course_lessions"=>$this->course_lessons(),
];
return $arr;
}
In the Controller you can write like this,
$course=Course::find(1)->course_details;
For more details t;
https://laravel.com/docs/5.7/eloquent-mutators
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
I wonder how to get all the sibling that a child have in laravel model ?
I know i can use this $siblings = \App\Child::all()->where('parent_id', $parent_id)->where('id', $id); to get all the child siblings, but I want to know if I can do the other way or more cleanest way?
So you can call this in the blade view $child->siblings->full_name something like that.
But I wonder how to use it something like this in the model.php
public function parent()
{
return $this->belongsTo(User::class);
}
with only using the belongsTo or hasMany function maybe if it's possible?
Sorry I'm not good with english so I don't know what it's called so I can search it on google.
Edit:: Adding Child.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Child extends Model
{
protected $guarded = [];
protected $dates = [
'birthdate',
'father_birthdate',
'mother_birthdate',
'guardian_birthdate',
];
public function parent()
{
return $this->belongsTo(User::class);
}
// I want to call this function only using $child->siblings (this one will show all the siblings)
// without passing the parent id
// to make it cleaner
public function siblings($parent_id)
{
return $this->all()->where('parent_id', $parent_id);
}
public function getAgeAttribute()
{
return Carbon::parse($this->attributes['birthdate'])->age;
}
public function getFullNameAttribute()
{
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
}
There are 2 ways you could do this.
1 creating the below method:
public function sibling()
{
return $this->belongsTo(User::class)->where('parent_id', $this->parent_id);
}
2 using a single Query:
$siblings = \App\Child::where('parent_id', $parent_id)->get();
Hope this helps
Update
A third way is:
public function scopeSiblings($query, $parent_id) {
return $query->where('parent_id', $parent_id)->get();
}
I'm working on a Laravel-5.4 project. I've three tables users, articles and comments in my database.
Screenshot of articles table:
Screenshot of comments table:
Article model:
class Article extends Model
{
public function comments() {
return $this->morphMany('App\Comment', 'commentable');
}
}
Comment model:
class Comment extends Model
{
public function commentable() {
return $this->morphTo();
}
}
ArticleController contains the following method:
public function showComments() {
return Article::find(1)->comments;
}
Above showComments() method returns [] (empty array). I want to return all the comments of the article which has id=1. What is the problem?
The commentable_type column should store the model name fully namespaced, such as App\User. Did you enter this information in manually? Try changing it to App\User, App\Article etc and see if that works.
You can create a morphMap in the boot method of your AppServiceProvider to alias these namespaces to a more descriptive name, as you have done here.
public function boot()
{
Relation::morphMap([
'User' => 'App\User',
// etc
]);
}
To import Relation:
use Illuminate\Database\Eloquent\Relations\Relation;
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.