One-to-many and one-to-many relationship 1 laravel - laravel

i did this(sorry my english it's bad bad....)
controller:
public function index()
{
$lessons = course::find(1)->lesson;
return view('home',compact('lessons'));
}
model lesson
public function course() {
return $this->belongsTo(Course::class);
}
model courses
public function lesson() {
return $this->hasMany(Lesson::class);
}
blade
#foreach ($lessons as $lesson )
<h4>{{$lesson->title}}</h4>
#endforeach
in browser nothing appears
why?:(

First rename your lesson method with plural lessons.
// Course model
public function lessons() // plural
{
return $this->hasMany(Lesson::class);
}
Now get the lesson's collection.
public function index()
{
$lessons = Course::find(1)->lessons;
return view('home', compact('lessons'));
}

#foreach ($lessons as $lesson )
<h4>{{$lesson->course->title}}</h4>
#endforeach

Have you tried it like this:
return view('greeting')->with('lessons', $lessons);
Now you can call '$lessons' in your view. Take a look at this link
https://laravel.com/docs/5.6/views
Can you try to use return $lessons; and show me what it says?

Related

Trying to get property 'designation_name' of non-object in Laravel 8

I want to show the user role from my user role table, but I can't.
User.php
public function role()
{
return $this->belongsTo('App\Models\Designation');
}
UserController
public function index()
{
$user = User::all();
return view('dashboard2', compact('user'));
}
View
<h1>{{ Auth::user()->role->designation_name}}</h1>
You actually should have shared more details about the relationships. But I will give an answer based on an assumption. It seems like there is a one-to-one relationship betwen User and Role as well as Role and Designation. So you want to reach designation from user. Based on that:
//User.php
public function role()
{
return $this->hasOne(Role::class);
}
//Role.php
public function user()
{
return $this->belongsTo(User::class);
}
public function designation()
{
return $this->hasOne(Designation::class);
}
//Designation.php
public function role()
{
return $this->belongsTo(Role::class);
}
// Controller
public function index()
{
// If you need only the auth user's data, you don't
// need adding relationships into the query.
$users = User::with('role.desgination')->all();
return view('dashboard2', compact('users'));
}
// View
// For auth user:
// I haven't used this way before,
// but technically it should work.
auth()->role()->designation()->name;
// For users collection:
// Make sure you added the query to the controller.
#foreach($users as $user)
$user->role->desgination->name
#endforeach

simple One to many relationship laravel

i have a user(ADMIN) and a student i want them to be in one table that is on the dashboard controller i cant find and exact answer in the searching please help me
Student model
public function user()
{
return $this->belongsTo("App\User", 'User_id', 'id');
}
User model
public function student()
{
return $this->hasMany("App\Student");
}
DashboardController
$users = User::with('user_id');
return view('superadminpage.admin_table')->with('users', $users);
Edit Student model code like this:
public function user(){
return $this->belongsTo("App\User");
}
Also edit User model:
public function students(){
return $this->hasMany("App\Student");
}
then use in DashboardController
$users = User::query()->with("students")->all();
return view('superadminpage.admin_table')->with('users', $users );
then you can do this:
foreach($users as $user){
$students = $user->students;
// use
}
first change the User_id to user_id at student model
public function user()
{
return $this->belongsTo("App\User", 'user_id');
}
second change at DashboardController
$users = User::with('user_id'); to $users = User::with('student')->all();
first change the User_id to user_id at student model
public function user()
{
return $this->belongsTo("App\User", 'user_id' , 'id');
}
second change at DashboardController
$users = User::with('user_id'); to $users = User::with('student')->all();
it's also good to change at user model public function student() to public function students() and call at DashboardController $users = User::with('students')->all();
public function users()
{
return $this->hasMany('App\User');
}
public function role()
{
return $this->belongsTo('App\Role');
}

Trying to retrieve posts from table by category slug

Hello i am trying to loop posts that are associated to each category by the slug. It works when i use the ids but when i change my controller function to search by slug it retrieves the slug but does not load the foreach loop.
I have tried so many methods and i don't know where i am going wrong please help.
Category Model :
protected $table = 'post_categories';
public function posts()
{
return $this->hasMany('App\Post', 'id', 'name', 'catslug');
}
Post Model
public function user()
{
return $this->belongsTo('App\User');
}
public function postCategories()
{
return $this->belongsTo('App\PostCategory');
}
Controller
public function getPostCategory($catslug) {
$postCategories = PostCategory::with('posts')
->orderBy('name', 'asc')
->where('catslug', '=', $catslug)
->first();
return view ('articles.category.categoriesposts')->with('postCategories', $postCategories);
}
Route
Route::get('articles/category/{catslug}', [
'uses' => 'ArticlesController#getPostCategory' ,
'as' => 'PostCategory'
] );
View
#foreach($postCategories->posts as $post)
<h4>{{ substr($post->title, 0, 50) }}</h4>
<p>{{ substr($post->body, 0, 90) }}</p>
#endforeach
When i use id there is no problem i cant see what i am doing wrong any feedback will be truly appreciated
Thanks
Ash
Save category id in posts table insted of category name or slug.
Change in post category model:
public function posts()
{
return $this->hasMany('App\Post', 'category_id');
}
Your controller method:
public function getPostCategory($catslug)
{
$postCategories = PostCategory::with('posts')->where('catslug', $catslug)->first();
return view('articles.category.categoriesposts')->with('postCategories', $postCategories);
}
If you want to order posts by name then add orderBy() in relationship :
public function posts()
{
return $this->hasMany('App\Post', 'category_id')->orderBy('name', 'asc');
}

Counting total posts by a user in the blade view

I have sent a collection of all posts in my blog to my index view and then used the following code to count the total posts made by each user.
<p class="joined-text">Posts: {{count(App\Posts::where('user_id', $post->user->id)->get())}}</p>
Is this bad practice to do this from within the blade view? If it is how would I achieve this?
Models
class Posts extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->hasMany(Comments::class, 'post_id');
}
}
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany('\App\Posts::class');
}
public function comments()
{
return $this->hasMany(Comments::class);
}
}
Simple solution:
<p class="joined-text">Posts: {{ App\Posts::where('user_id', $post->user_id)->count() }}</p>
Updated
Complete and better solution:
Post.php:
public function user(){
return $this->belongsTo(App\User::class);
}
User.php:
public function posts(){
return $this->hasMany(App\Post::class);
}
public function getPostsCountAttribute(){
return $this->posts()->count();
}
blade:
<p class="joined-text">Posts: {{ $post->user->posts_count }}</p>
Yes it is bad.
You could use relationships if have the user_id field in posts table
class User extends Model
{
public function posts()
{
return $this->hasMany('App\Post');
}
}
In controller
return view('sth')->with(['posts'=>$user->posts]);
Then in view
$posts->count();
Or just getting counts if you don't need posts
$postCount = $user->posts()->count();

Laravel Retrieve related model through pivot table

So i'm a bit confused with this situation, I have the current relations:
User hasmany Favourite
favourites references to a Recipe model
favourites is a pivot table but when I retrieve the favourites for a given user like:
$user->favourites
i get the favourite with the pivot data, but I want to get the fields of the recipe
Recipe.php:
public function favourites()
{
return $this->hasMany('App\Favourite');
}
User.php:
public function favourites()
{
return $this->hasMany('App\Favourite');
}
Favourite.php:
public function user()
{
return $this->belongsTo('App\User','user_id');
}
public function recipes()
{
return $this->belongsTo('App\Recipe','recipe_id');
}
EDIT : there was no problem at all, just needed to call:
#foreach($user->favourites as $favourite)
{{ $favourite->recipe->name }}
#endforeach
You need to set your relation to Has Many Through instead of just has Many.
https://laravel.com/docs/5.2/eloquent-relationships#has-many-through
Recipe.php:
public function favourites()
{
return $this->hasManyThrough('App\Favourite', 'App\User');
}
User.php:
public function favourites()
{
return $this->hasManyThrough('App\Favourite', 'App\Receipe');
}
Favourite.php:
public function user()
{
return $this->hasManyThrough('App\User','App\Receipe');
}

Resources