belongsTo() function not working - laravel

I am trying to make a relation with my Character table and Account table but when I add the belongsTo() method I don't see the data of Account added to it.
So this is my Character model:
class Character extends Model
{
//Get players by level
public function scopeGetPlayersByLevel($query){
return $query->orderBy('level', 'desc')->get();
}
//Get players by zulie
public function scopeGetPlayersByZulie($query){
return $query->orderBy('zuly', 'desc')->get();
}
//Get online status
public function account(){
return $this->belongsTo(Account::class, 'username', 'account_name');
}
}
Account model:
class Account extends Model
{
//Get online players
public function scopeGetOnlinePlayers($query){
return $query->where('online', 1);
}
//Get online staff
public function scopeGetOnlineStaff($query){
return $query->where('online', 1)->where('accesslevel', 350);
}
public function characters(){
return $this->hasMany(Character::class, 'account_name', 'username');
}
}
And I add the variable in my controller like this:
use App\Character;
class RankingController extends Controller
{
function index(){
$players = Character::find(100);
return $players;
}
}
Table structure:
accounts:
- username
characters:
- account_name //foreign key
The result of $players is only the character data. Why doesn't the account data add to it?

If I understand what you are trying to do is you are trying to get a player and all their characters.
try
function index(){
$player = Account::find(1);
return $player->characters;
}
Find the account of a character
$caracter = Character::find(1);
return $caracter->account;

Try this:
//Get online status
public function account(){
return $this->belongsTo(Account::class, 'account_name', 'username');
}

Related

Laravel associate relationships by model instance dynamically

In my Laravel 9 project, My User Model is belongs to 3 models (Distributor, Agency and Advertiser) like:
public function distributor()
{
return $this->belongsTo(Distributor::class);
}
public function agency()
{
return $this->belongsTo(Agency::class);
}
public function advertiser()
{
return $this->belongsTo(Advertiser::class);
}
And I use this function to associate in my DistributorRepository(and other 2 model's repositories):
public function associateUser($id, $user_id)
{
$user = $this->user->find($user_id);
$distributor = $this->find($id);
$result = $user->distributor()->associate($distributor)->save();
return $result;
}
Now, I want to modify to associate them by user's id and relation model instance (Distributor, Agency and Advertiser) in my UserRepository (or UserService) dynamically, like:
public function associate($id, $modelInstance)
{
// Something happens here
}
Is that possible and how to do? Thanks!
If I understand right, then you can do it with:
public function associate($user_id, $parentModelInstance)
{
$user = User::find($user_id); //or how ever you get user in repository
$reflect = new ReflectionClass($parentModelInstance);
$relationName = Str::lower($reflect->getShortName()); //magic for getting relation (if class name is relation name)
return $user->{$relationName}()->associate($parentModelInstance)->save();
}
And you can use it like this:
$distributor = Distributor::find(1);
$user_id = 1;
$this->associate($user_id, $distributor)

Laravel query builder with the User and Auth

How to List all rows from a table (agendas) in my DB where records are saved by the connected user.I'm using default Auth from Laravel.
public function index ($id = null)
{
$agendas = Agenda::where('id', Auth::user()->id)->get();
$users = User::all();
return view('admin.agendas.index', compact('agendas','users','id'));
}
My controller here.
Need help
Assuming
agendas table (containing records for Agenda model) has a column user_id which references the id column on users table
User hasMany Agenda
Agenda belongTo User
class User extends Model
{
public function agendas()
{
return $this->hasMany(Agenda::class);
}
//... rest of class code
}
class Agenda extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
//... rest of class code
}
public function index($id = null)
{
$user = User::with('agendas')->findOrFail(auth()->id());
return view('admin.agendas.index', [
'user' => $user,
'agendas' => $user->agendas,
'id' => $id
]);
}
Your User model should have a relationship:
public function agendas()
{
return $this->hasMany(Agenda::class);
}
In your controller, you could then simplify the use as such:
public function index (Request $request, $id = null)
{
$agendas = $request->user()->agendas;
$users = User::all();
return view('admin.agendas.index', compact('agendas','users','id'));
}
if you wanna get data related to another data , you have to join those tables together by a field. in this case i guess you have a column in Agenda table named 'user_id'.
you have two way :
join tables in your Model.
search in Agenda table in your controller
if you want to use joining your tables from model :
// in App\User.php
...
class User ...{
...
public function Agenda(){
return $this->hasMany(Agenda::class);
}
...
}
...
then you can access to all of "Agenda" from everywhere like this :
Auth()->user()->agenda
if you want to search in table from your controller you can do :
Agenda::where('id', Auth::user()->id)
you can read more about eloquent-relationships in : https://laravel.com/docs/8.x/eloquent-relationships

Getting extra fields from laravel api having belongstomany relationship

I have two data tables related to each other by the belongstomany relationship. And when I am fetching data from its api controllers with selecting only two column keys ['id','title'] yet it returns some extra data in the response object.
modelcode:
public function place(){
return $this->belongsToMany(Place::class,'city_place')->select(array('id', 'title'));
}
controller code:
public function ofcity($id)
{
$city=City::findOrFail($id);
return new CityResource( $city->place()->get());
}
enter image description here
You must indicate the name of the table in front of the fields.
model Place code:
protected $columns = ['places.id', 'places.title']; //all column for select
public function scopeExclude($query, $value = [])
{
return $query->select(\array_diff($this->columns, (array) $value));
}
model City code:
public function place()
{
return $this->belongsToMany(Place::class,'city_place', 'city_id', 'place_id');
}
controller code:
public function ofcity($id)
{
$cities = City::findOrFail($id)->place()->exclude(['featured_image'])->get()->toArray();
return response()->json(['cities' => $cities], 200);
}
In exclude skip all the fields that need not to be shown.
Thanks everyone here helping me out but none of the above solution worked..I figured it out after trying different functions and spending hours on this.
model Place code:
public function place(){
return $this->belongsToMany(Place::class,'city_place','city_id','place_id')->select(array('places.id', 'places.title'));
}
controller code:
public function ofcity($id)
{
$city=City::findOrFail($id);
return new CityResource( $city->place()->get()->map(function ($item,$key) {
return ['id' => $item['id'],'title'=>$item['title']];
})
);

Need help laravel 4.2

I want to get the username in table user, of post ID in post table and return View::make('post.index'). I need to view in post.index blade.
Database
users table
id
username
post table
id
message
posts_id
Post.php #models folder
public function posts()
{
return $this->belongsTo('User');
}
User.php #models folder
public function post()
{
return $this->hasMany('Post');
}
PostController.php #controller folder
public function index()
{
$posts = Post::with('username')->get();
return View::make('post.index')->with('posts', $posts);
}
post/index.blade.php
the result here
i need to the result of author id become the username
for the best practices:
your model class names should be User and Post. database table names should be users and posts.
in Post.php file ,
public function user()
{
return $this->belongsTo('User');
}
in User.php file,
public function posts()
{
return $this->hasMany('Post');
}
in your PostController.php
public function index()
{
$user_of_the_post = Post::find(postId)->user; //replace the postId //this will return the user object of the specified post
$user_name_of_the_author = $user_of_the_post->username;
**pass the necessary data to the view and print and return the view**
}

Laravel Eloquent hasMany and BelongsToMany not returning using with

I am trying to do a single query to get back an order and the card to charge, but getting an error.
Card model:
class Card extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function orders()
{
return $this->hasMany('Order');
}
}
Order model:
class Order extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function card()
{
return $this->hasOne('Card');
}
public function address()
{
return $this->belongsTo('Address');
}
public function orderItems()
{
return $this->hasMany('OrderItem');
}
}
What I am trying to get back:
$order = Order::with('card')->find($id);
This obviously doesn't work and I have tried several combos. I think the issue is with my models/relationships.
Any idea how I can get back the order with the card/token details?
DB info: Each order can have only one card_id and each card can be in many orders. There is no order_id in the card.
Orders table basically:
id | card_id
Cards table:
id | token
Trying to get the token col to return with the Order.
In your Order model, you need to change this:
public function card()
{
return $this->hasOne('Card');
}
to this:
public function card()
{
return $this->belongsTo('Card');
}
The reason is that you are defining the inverse of the hasMany relationship. With the belongsTo relationship, Eloquent will look for a card_id column on the orders table.

Resources