simple One to many relationship laravel - 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');
}

Related

How would I edit the Laravel Nova indexQuery for a Resource to only show records through multiple relationships?

firstly thank you in advance.
I have the following Models , User , Location, Listing, Offer.
The relationships are:
User Model:
public function location()
{
return $this->hasOne(Location::class);
}
Location Model:
public function listings()
{
return $this->hasMany(Listing::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Listing Model:
public function offers()
{
return $this->hasMany(Offer::class);
}
public function location()
{
return $this->belongsTo(Location::class);
}
Offer Model:
public function listing()
{
return $this->belongsTo(Listing::class);
}
In my Offer Resourse I would like to show only the offers that belongTo the listings that in turn belongsTo the location that in turn belongTo the authenticated user. I have tried the following.
public static function indexQuery(NovaRequest $request, $query)
{
$user = Auth::user();
if ($user->is_admin === 1){
return $query;
}elseif($user->is_admin === 0) {
return $user->location->listings->offers;
}
}
But get an error Property [offers] does not exist on this collection instance. Any assistance will be greatly appreciated.
I would try something like this.
More information here on querying relationship existence:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence
public static function indexQuery(NovaRequest $request, $query) {
$user = Auth::user();
if (!$user->is_admin) {
$query = $query->whereHas('listings.location.user', function ($builder) use ($user) {
return $builder->where('id', $user->id);
});
}
return $query;
}
The reason you are getting the "Property does not exist" error is due to you not pulling it from database.
Two alternative solutions include
Querying them separately: ...->listings()->offers()
Eager loading: ->with(['location.listings.offers']);

How to get pivot data depends model binding

I am using in Pivot model. In previously i assigned user_id is routekey but now i want to match model binding flats (flat_id) also. I have attached the output screenshot too.
My url is http://127.0.0.1:8000/admin/apartments/1/flats/2/flat-members/3
namespace App\pivotes;
use Illuminate\Database\Eloquent\Relations\Pivot;
use App\models\RoleUser;
use App\models\Flat;
use App\models\Association;
use App\models\Role;
use App\User;
class FlatUser extends Pivot
{
protected $table = 'flat_user';
public $timestamps = false;
public function getRouteKeyName()
{
return 'user_id';
}
public function flat()
{
return $this->belongsTo(Flat::class, 'flat_id', 'id');
}
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id', 'id');
}
}
Update I tired this
In RouteServiceProvider
public function boot()
{
parent::boot();
Route::bind('flat_member', function ($value) {
dd(\App\pivotes\FlatUser::where('flat_id', request()->route()->parameter('flat'))->where('user_id', request()->route()->parameter('flat_member'))->first());
return \App\pivotes\FlatUser::where('flat_id', request()->route()->parameter('flat'))->where('user_id', request()->route()->parameter('flat_member'))->first() ?? abort(404);
});
}
for dd() I am getting correct data, but if I am returning it, it seems to be becoming empty.
I am using RouteServiceProvider.php. I check flat_id and route parameter flats whether it matches, giving particular pivot model data. In below added my codes.
public function boot()
{
parent::boot();
Route::bind('flat_member', function ($value) {
return \App\pivotes\FlatUser::where('flat_id', request()->route()->parameter('flat'))->where('user_id', request()->route()->parameter('flat_member'))->first() ?? abort(404);
});
}

Laravel scout check if relation is not empty?

namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;
class Event extends Model
{
protected $table = 'events';
public $timestamps = true;
use Searchable;
use SoftDeletes;
protected $dates = ['deleted_at'];
public function entities()
{
return $this->belongsTo('App\Entity', 'entity_id');
}
public function users()
{
return $this->belongsTo('App\User', 'id');
}
public function events()
{
return $this->belongsTo('App\DirtyEvent', 'id');
}
public function toSearchableArray()
{
$data = $this->toArray();
$data['entities'] = $this->entities->toArray();
return $data;
}
}
This is my model for Event, as you can see I am using toSearchableArray which is Laravel scout function to import 'relations' to algolia. However the problem is that sometimes it is empty. So for example
event id 1 has entity_id 1
but in another example
event id 2 has entity_id = null
How can I modify this function to check if the entities() relation is not empty before putting it into array?
if i understand u correctly this should help. if the relationship does not exist return an empty array and scout won't update the index
public function toSearchableArray()
{
if(is_null($this->entities)){
return [];
}
$this->entities
return $this->toArray();
}
please update foreign_key in relation as this
user_id as foreign_key instead of id
event_id as foreign_key instead of id
public function users()
{
return $this->belongsTo('App\User', 'user_id');
}
public function events()
{
return $this->belongsTo('App\DirtyEvent', 'event_id');
}
I think if load the relation before the toArray().
public function toSearchableArray()
{
$this->entities;
return $this->toArray();
}

how to save data in multiple tables with the one form

I have 2 tables: customers and address one form to save data into this tables. For this, I made the relation like:
Address model
public function customer()
{
return $this->belongsTo(Customer::class);
}
customer model
public function address()
{
return $this->hasMany(Address::class);
}
How can i save the address in table? I already done with customer i can save, update and delete. I read the DOC of Eloquent of laravel, but i don't really get it.
Here is my controller
class CustomerController extends Controller
{
public function index()
{
// $customer = Customer::all();
$customer = Customer::with('address')->get();;
return view('customer.index', compact('customer'));
}
public function create(Address $address)
{
$address = $address->all();
return view('customer.create');
}
public function store(CustomerRequest $request , Customer $customer)
{
$customer = Customer::create($request->all());
return redirect()->route('customer.index',compact('customer'));
}
public function show(Customer $customer)
{
return view('customer.show',compact('customer'));
}
public function edit(Customer $customer)
{
return view('customer.edit', compact('customer'));
}
public function update(CustomerRequest $request, $id)
{
$customer = Customer::find($id)->update($request->all());
return redirect()->route('customer.index',compact('customer'));
}
public function destroy($id)
{
Customer::destroy($id);
return redirect()->route('customer.index');
}
}
Any suggestions would be appreciated!!

Laravel - Retrieving specific column from a releted query

I have 4 tables:
conversations
- id (pk)
- userId1 (fk)
- userId2 (fk)
users
- id (pk)
- name
- surname
.
.
.
- roleId (fk)
- userStatusId (fk)
roles
- id (pk)
- type (fk)
user_status
- id (pk)
- description (fk)
this are my models:
class Conversation extends Eloquent {
public function user1(){
return $this->hasOne('User', 'id', 'userId1');
}
public function user2(){
return $this->hasOne('User', 'id', 'userId2');
}
}
class User extends Eloquent {
public function role(){
return $this->hasOne('Role', 'id', 'roleId');
}
public function userStatus(){
return $this->hasOne('UserStatus', 'id', 'userStatusId');
}
// public function conversation1(){
// return $this->belongsToMany('Conversation', 'id', 'userId1');
// }
// public function conversation2(){
// return $this->belongsToMany('Conversation', 'id', 'userId2');
// }
}
class UserStatus extends Eloquent {
public $timestamps = false;
protected $table = 'user_status';
public function user(){
return $this->belongsToMany('User', 'id', 'userStatusId');
}
}
class Role extends Eloquent {
public $timestamps = false;
public function user(){
return $this->belongsToMany('User', 'id', 'roleId');
}
}
Now what I want to do is, for example, take all the conversations where the "userId1" (on conversations) is of a "user" who have the status "description" equal to "registered".
That's what I do:
Route::get('/', function(){
$conversation = Conversation::with(array('user1.userStatus' => function ($query){
$query->where('description', '=', 'registered');
}))->get();
foreach ($conversation as $conv) {
echo '<br \>';
echo $conv;
}
});
I expect to receive all the conversations record where the status of the userId1 is "registered" and nothing else... Instead what I receive are all the conversations records and, for each one, the user records and the records of the userStatus table (of this last I receive just the one who match the where clause and the ones who are not have a null value).
I know my english is terrible but I hope someone could understand and help me. Thanks!
All your relations are wrong. You need to read http://laravel.com/docs/eloquent#relationships and in your case it's:
class Conversation extends Eloquent {
public function user1(){
return $this->belongsTo('User', 'userId1');
}
public function user2(){
return $this->belongsTo('User', 'userId2');
}
}
class User extends Eloquent {
public function role(){
return $this->belongsTo('Role', 'roleId');
}
public function userStatus(){
return $this->belongsTo('UserStatus', 'userStatusId');
}
}
class UserStatus extends Eloquent {
public $timestamps = false;
protected $table = 'user_status';
public function user(){
return $this->hasMany('User', 'userStatusId');
}
}
class Role extends Eloquent {
public $timestamps = false;
public function user(){
return $this->hasMany('User', 'roleId');
}
}
Now, to retrieve only those conversations you want this:
Conversation::whereHas('user1', function ($q) {
$q->whereHas('userStatus', function ($q) {
$q->where('description', 'registered');
});
})->get();
or using this PR https://github.com/laravel/framework/pull/4954
Conversation::whereHas('user1.userStatus', function ($q) {
$q->where('description', 'registered');
})->get();
Also, to make it more verbose, you can wrap that code in a scope:
// User model
public function scopeRegistered($query)
{
$q->whereHas('userStatus', function ($q) {
$q->where('description', 'registered');
});
}
then:
Conversation::whereHas('user1', function ($q) {
$q->registered();
})->get();
You may try this:
$conversations = Conversation::whereHas('user1.userStatus', function ($query){
$query->where('description', '=', 'registered');
})->get();
This will return only the Conversation models whose related user1.userStatus is registered.

Resources