I have two tables users and user_details. I have linked users table as
public function userDetails()
{
return $this->hasOne('App\Repositories\Models\UserDetails', 'id', 'user_id');
}
and linked user_details table as
public function user()
{
return $this->belongsTo('App\Repository\Models\User');
}
While from UserController for accessing users data with details, if I try to access the data
return $this->user->with('userDetails')->get();
I get this type of error
FatalErrorException in HasRelationships.php line 488: Call to undefined method
App\Repositories\Models\UserDetails::getConnectionName()
Is there anything wrong?
Make sure UserDetails class extends Model class:
use Illuminate\Database\Eloquent\Model;
class UserDetails extends Model
You can also clean up your code like this. Having neat code will make your code more valuable and it will be easier for other developers to understand or you to remember when you get back to your code later on.
use Illuminate\Database\Eloquent\Model;
use App\Repository\Models\User;
use App\Repository\Models\UserDetails;
public function user()
{
return $this->belongsTo('User');
}
public function userDetails()
{
return $this->hasOne('UserDetails', 'id', 'user_id');
}
Related
I have a pivot table post_profile that contains the hearts (likes) of each post.
Post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function profilesHearted()
{
return $this->belongsToMany(Profile::class);
}
}
Profile.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function profileImage()
{
$imagePath = ($this->image) ? $this->image : 'profile/czyhBQu2YWX6gvBivZrnEs2ORoBwr3d9mzkwxk8k.png';
return $imagePath;
}
public function followers()
{
return $this->belongsToMany(User::class);
}
public function heartedPosts()
{
return $this->belongsToMany(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
The main view which shows all posts of followed users is working along with the heart button but underneath I want to show liked by <x> and 30 others, where x is first follower of the user if any of the user's follower hearted the post. I tried many ways to get x but I am a bit lost.
This is PostsController.php index function which leads to the view:
public function index()
{
$users = auth()->user()->following()->pluck('profiles.user_id');
$posts = Post::whereIn('user_id', $users)->with('user')->latest()->paginate(5);
return view('posts.index', compact('posts', 'users' ));
}
What I tried to do but deleted eventually after failing is get each post in foreach loop and check if each $post->heartedProfiles(contains($users)), but this doesn't work this way. So another way I tried is in my view ie, index.blade.php
#foreach($users as $userid)
User::select('id')->where('profile_id', $userid)->first()
->profile->profilesHearted->find($post->id)
#endforeach
Which doesn't work because User class cannot be used directly in view without passing.
I'm sure there is a simple and cleaner way to do this in Laravel. This is my first time using Laravel and ORM programming so really felt lost. Took the FreeCodeCamp Instagram clone tutorial and understood the basics. All I need is to give me some idea to get started.
When dealing with many to many you need to use the pivot functions, so you would do like so
Post::profilesHearted()->wherePivotIn('profile_id', $users)->first()
Not checked the code but hopefully it will give you the idea.
I used laravel Auditor in a model and it works very well as following:
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
class Contracts extends Model implements Auditable
{
use \OwenIt\Auditing\Auditable;
protected $fillable=['condatereceived'];
public function user()
{
return $this->belongsTo(User::class);
}
}
But I want to used it in the controller as :
public function updatecomplated(Request $request, $id,Contracts $contract ,Auditor $auditor)
{
Contracts::where('id', $id)
->update(['complated' => 50, 'conuploadby' => Auth::id(),'constatus' =>'Need To Active' ]);
if ($audit = $auditor->execute($contract)) {
$auditor->prune($contract);
}
return redirect()->back();
}
The code in controller give me error:
Call to undefined method OwenIt\Auditing\Facades\Auditor::execute()
any ideas to use auditor in the controller, please.
try this package its easy with good documentation
simply add this to your table
$table->auditable();
and this to your model
namespace App;
use Yajra\Auditable\AuditableTrait;
class User extends Model
{
use AuditableTrait;
}
thats it now simply get your auditor by calling
$user->creator // for who create
and
$user->updater //for who update data
for more information click here for check trait
Hope this helps
Let say i have the following;
User Model;
class User extends Authenticatable
{
public function posts()
{
return $this->hasMany('App\Models\Socials\Post');
}
}
Post Model;
class Post extends Model
{
public function comments()
{
return $this->morphMany('App\Models\Socials\Comment', 'commentable');
}
Comment model;
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
When i used $user = User::find($id); and $user->posts(), it returns all the post of the user, but if i used this method $user->posts()->comments() It return this message Method Illuminate\Database\Query\Builder::comments does not exist.
The question is how can i get all the comments of the user on the said post?
Change:
$user->posts()->comments();
to:
$user->posts->pluck('comments')->collapse();
The method itself returns an instance of Eloquent's query builder allowing you to add to or edit the query if you want. However, if you don't want to edit the query you can access the relationships as properties and Laravel will handle to execution of the query.
Essentially, $user->posts is actually turning into $user->posts()->get() in the background.
Credit to #JonasStaudenmeir.
In Laravel 5.6 I'm trying to load data into the user object, so I can view user credentials/settings etc.
Whats annoying is I had it working, but for some reason now It seems to have stopped, and I'm not sure what I've changed to break it.
Anyway I want to load two tables, access and settings. Both of them have user_id field in there with the corresponding user_id in.
In my User.php class I have two functions:
public function access() {
return $this->hasMany(Access::class);
}
public function settings() {
return $this->hasOne(Settings::class);
}
I am not Use-ing them at the top of the class (i.e. use \App\Access) if that makes any difference.
And then the Access class looks like:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Access extends Model
{
protected $table = "access";
}
And the Settings class is very much the same:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Settings extends Model
{
protected $table = "settings";
}
However whenever I try and access Auth::user()->settings or Auth::user()->access I get undefined index: error. It's frustrating because like I said I had it working the other day and I'm not sure what's changed.
Few things you could try here. First, Lazy Eager Load the relationships by loadMissing:
// settings
Auth::user()->loadMissing('settings');
// access
Auth::user()->loadMissing('access');
To load a relationship only when it has not already been loaded, use the loadMissing method
Second, you can use with when querying for a user, although it's not as relevant with using the auth facade:
User::with(['settings', 'access'])->where('atribute', $value)->get();
Last, if you always want the settings and access relationships to always be returned with each user model, set the with attribute on the user model:
public class User {
protected $with = ['settings', 'access'];
...
}
I usually define the inverse relationships on models as well, so Access and Settings would have a BelongsTo relationship defined:
class Access extends Model
{
protected $table = "access";
public function user() {
return $this->belongsTo(User::class);
}
}
class Settings extends Model
{
protected $table = "settings";
public function user() {
return $this->belongsTo(User::class);
}
}
I am busy with Laravel From Scratch: Updating Records and Eager Loading. I have followed the tut but I am getting this error when trying to add user data in CardsController. I am assuming that I've missed a step in the card user relationship somewhere but I've watched the video 3 times and my database queries for User, Card & Note matches the video exactly.
Is there another step I need to perform after creating the Users table via the migration perhaps?
Error
BadMethodCallException in Builder.php line 2345:
Call to undefined method Illuminate\Database\Query\Builder::user()
CardsController code
<?php
namespace App\Http\Controllers;
use App\Card;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CardsController extends Controller
{
public function index()
{
$cards = Card::all();
return view('cards.index', compact('cards'));
}
public function show(Card $card)
{
$card = Card::with('notes.user')->get();
return $card;
return view('cards.show', compact('card'));
}
}
Your note model is lacking the relationship definition for it's associated user, it looks like.
You should just be able to add the relationship in the Notes model like this:
public function user()
{
return $this->belongsTo(User::class);
}
That video does have some problems, so I also encountered the same problem.
You should just be able to add the relationship in the Note model like this:
public function user()
{
//return $this->belongsTo(User::class);
return $this->belongsTo('App\User');
}
and in the User model like this:
public function notes()
{
return $this->hasMany(Note::class);
//return $this->belongsTo('App\Note');
}
bless you !