laravel 8 auth::user collection from tables - php

I am new to laravel 8 and blade syntax.
I am working on a project where users (agents) can upload apartments.
i have agent table with corresponding model relationship
agent model
public function property()
{
return $this->hasMany(Property::class, property_id, id);
}
property model
public function agents()
{
return $this->belongsTo(Agent::class, agent_id, id);
}
I used breeze to build up my registration and login
i want when an agent is logged in, i will display in his dash board list of his properties.
#foreach(Auth::user()->properties as $property)
#if(($loop->count) > 0)
<td class="py-3 px-2">
<div class="inline-flex space-x-3 items-center">
<span>{{$property->propertyId}}</span>
</div>
</td>
<td class="py-3 px-2">{{$property->building}}</td>
<td class="py-3 px-2">{{$property->rent->name}}</td>
#else
You have not uploaded any apartment
#endif
#endforeach
but i get error "Undefined variable $properties".
Meanwhile, {{ Auth::user()->othernames }} works fine.
AgentController
public function index()
{
return view ('dashboard', [
'agent' => Agent::all(),
'appointment'=>Appointment::all(),
'properties'=>Property::all(),
'schedule'=>AgentSchedule::all()
]);
}
propertyController
public function create()
{
return view('pages.uploadapartment', [
'states'=> State::all(),
'areas'=>Area::all(),
'buildings'=>building::all(),
'buildingtypes'=>BuildingType::all(),
'rentpaymentmethods'=>rentpaymentmethod::all(),
'flattypes'=>flattype::all(),
]);
}

Since you are not using user model to define the relationship!
Your relationship should be like this:
//In your agent model
public function properties()
{
return $this->hasMany(Property::class, 'property_id', 'id');
}
//In property model
public function agent()
{
return $this->belongsTo(Agent::class, 'agent_id', 'id');
}
And when you want properties from a logged-in user, you grab them like this: $properties = Auth::user()->properties;

Related

How to get username from users table in laravel?

Here is the Controller code I have
public function index()
{
$ajobs = Job::all();
return view('jobs_all', ['jobs' => $ajobs]);
}
This shows all my Table Data. I have stored user id as another column named created_by
In the View, I get value by ID, how how can I get the Username from Users table.
#foreach ($jobs as $ajob)
{{ $ajob->created_by }} //Here instead of UserID, how can i get Username by matching the UserID with UsersTable ?
#endforeach
Add next method to your "Job" model:
public function user(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
now you can add ORM param "with" to your method "index":
public function index() {
$ajobs = Job::with('user')
->all();
return view('jobs_all', ['jobs' => $ajobs]); }
now we have access to user model fields, and you can show them this way:
#foreach($jobs as $ajob)
{{ $ajob->user->name }}
#endforeach
More info about laravel relations here: https://laravel.com/docs/8.x/eloquent-relationships#one-to-one
you can use laravel eloquent belongsTo relationship. in your Job model add the following method.
public function user()
{
return $this->belongsTo(User::class, 'created_by');
//assuming your user model name is User and both models are in the same namespace. if not, adjust according to your structure.
}
and then you can use this relationship to get the user name like
#foreach ($jobs as $ajob)
{{ $ajob->user->name }}
//name is the column name from the user table. change if necessary.
#endforeach
You can use relations but in fast way on your situation you can join your tables:
$user_id = DB::table('jobs')
->select('users.id')
->join('jobs', 'jobs.user_id', '=', 'users.id')
->get();
=> add on your job table as foreginId user
$table->timestamp('created_at')->useCurrent();
$table->foreignId('created_by')->constrained('users')->onUpdate('cascade')->onDelete('cascade');
**That Function add on job model**
public function getCreatedAttribute()
{
return ucfirst($this->user->name);
}
=>relationship add on job table
public function user()
{
return $this->belongsTo(User::class,'id','created_by');
}
=>created display your user name
#foreach ($jobs as $ajob)
{{ $ajob->created}}
#endforeach
=>listing controller
public function index() {
$jobs = Job::with(['user']);
return view('jobs_all', compact('jobs')); }

Display one image from database in laravel

I have two tables in Laravel
jalans
jalan_images
In one id_jalan can be many images, My relations like this
Model Jalan
// Model Jalan
public function jalanImage()
{
// return $this->hasMany('App\JalanImage', 'id_jalan');
return $this->hasMany(JalanImage::class, 'id_jalan');
}
public function firstImage()
{
// return $this->hasOne('App\JalanImage', 'id_jalan');
return $this->hasOne(JalanImage::class, 'id_jalan');
}
Model JalanImage
// Model JalanImage
public function jalan()
{
// return $this->belongsTo('App\Jalan', 'id_jalan', 'id');
return $this->belongsTo(Jalan::class, 'id_jalan', 'id');
}
I want to display data like title, created_at, and the first image in each id_jalan, in my Controller for display data like this
JalanController
// JalanController
public function jalan()
{
$jalan = Jalan::with('firstImage')->orderBy('created_at', 'DESC')->get();
return view('jalan.all', ['jalan' => $jalan]);
// dd($jalan->toArray());
}
In my view, first image from each id_jalan not displayed, my view like this
Blade View
#foreach($jalan as $row)
<div class="post-item clearfix">
<table border="0">
<tr>
<td width="170px">
<a href="#">
<img src="{{ asset('uploads/jalan/' .$row->first_image) }}" alt="" class="img-fluid" width="150px"></td>
</a>
<td>
<h4>{{ $row->title }}</h4>
<i class="icofont-wall-clock"></i> <time>{{ date('d F Y', strtotime($row->created_at)) }}</time>
<p style="color: #F3591F">{{ $row->category }}</p>
</td>
</tr>
</table>
</div>
#endforeach
When I display it with dd($jalan->toArray()); in my controller, the first_image displayed.
How to fix it?
Thank you
You should follow Laravel's (especially Eloquent's) advices and best practices regarding naming convention. That means your gallery_images table should have gallery_id field instead what you have there. Believe or not, that way you'll skip lot of unforced errors and questions. I will leave you answer of how I would do it in your place:
// \App\Gallery::class
class Gallery extends Model
{
public function galleryImages()
{
return $this->hasMany(GalleryImage::class);
}
public function firstGalleryImage()
{
return $this->hasOne(GalleryImage::class);
}
}
// \App\GalleryImage::class
class GalleryImage extends Model
{
public function gallery()
{
return $this->belongsTo(Gallery::class);
}
}
Basically you can set as many as you need methods in model that returns specific relation. In Gallery::class here, you can see I have set one more relation that would return just first image of that gallery. In controller you'd call it with
public function someControllerMethod()
{
$gallery = Gallery::with(['firstGalleryImage'])->first();
// or
$galleries = Gallery::with(['firstGalleryImage'])->get();
}
Now returned object $gallery or collection of $galleries would carry only first image related. In your case (and if you don't want to change names of fields) you need to follow documentation of how to set another model's keys as method's arguments.
you can use Laravel's Eloquent ORM ( Eager Loading ),
here is an example of a single Image(image) and multiple images (media) relationship.
public function media()
{
return $this->hasMany(Media::class, 'foreign_key', 'local_key');
}
public function defaultMedia()
{
return $this->hasOne(Media::class, 'foreign_key', 'local_key');
public function image()
{
return $this->defaultMedia();
}

Many to Many Relationship return trying to get property 'books' of non-object

I am trying to displaying the book a user has favorited, so I think many to many relationships will solve it. So I have 3 tables
Users Table
Books Table
Favorite Table
The Favorite table is the pivot table
Schema::create('favorites', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('book_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
In the User Model
public function favorites(){
return $this->hasMany(Favorite::class);
}
In the Book Model
public function favorites()
{
return $this->hasMany(Favorite::class);
}
In my Favorite Model
public function book ()
{
return $this->belongsTo(Book::class);
}
I was able to save to Favorite Column like this
public function favorite($id)
{
Favorite::create([
'book_id' => $id,
'user_id' => Auth::id()
]);
Session::flash('success', "You Favorite a Book");
return redirect()->back();
}
But I am trying to show the Books Favorited
public function mylibrary(){
$user = Auth::user()->books;
// dd($user);
return view('library', compact('user'));
}
In my view, I have this
#foreach($user->books as $mybook)
...
<div class="clearfix"></div>
<p class="authorone">{{ $mybook->author->name }}</p>
<h1 class="book-title">{ $mybook -> title }}</h1>
</div>
#endforeach
You are passing Auth::user()->books to your view, not Auth::user(). You are not passing the User.
In the view you are then trying to use that value as an object:
#foreach ($user->books as $mybook)
Auth::user()->books is most likely returning null since it is not a relation method or an attribute (most likely).
You probably want to pass the User to your view:
view(..., ['user' => Auth::user()]);
Then you would want to access the correct dynamic property for the relationship you want since you aren't showing a books relationship on User.
Your model relationships could use a better setup. There is no Many to Many setup here and you don't need to define a model for the pivot, you are actually avoiding the Many to Many by doing this.
Models:
class User
{
public function books()
{
return $this->belongsToMany(Book::class, 'favorites');
}
}
class Book
{
public function users()
{
return $this->belongsToMany(User::class, 'favorites');
}
}
Controller:
public function favorite($id)
{
Auth::user()->books()->attach($id);
...
}
public function mylibrary()
{
$user = Auth::user()->load('books.author');
return view('library', compact('user'));
}
View:
#foreach($user->books as $mybook)
...
<div class="clearfix"></div>
<p class="authorone">{{ $mybook->author->name }}</p>
<h1 class="book-title">{{ $mybook->title }}</h1>
</div>
#endforeach
I was able to solve it this way
My view
#forelse ($user->favorites as $mybook)
<p class="authorone">{{ $mybook ->book->author-> name }}</p>
<h1 class="book-title">{{ $mybook ->book-> name }}</h1>
#empty
<h2>You haven't Favorited any book</h2>
<div class="text-center">
Return To
</div>
#endforelse
I added this to my user model
public function favorites(){
return $this->hasMany(Favorite::class);
}
public function books()
{
return $this->belongsToMany(Book::class);
}
My controller
public function mylibrary(){
return view('library', ['user' => Auth::user()]);
}

Showing Empty after using eloquent un laravel

I have MyRoom.php and TotalCity.php in my project in which each room is categorizes inside a city
so that I did this in MyRoom.php
public function location()
{
return $this->belongsTo(TotalCity::class, 'location_id')->withTrashed();
}
and I did this in TotalCity.php
public function location()
{
return $this->hasMany(MyRoom::class , 'total_city_id')->withTrashed();
}
I have passed id with routes and controller like this
home.blade.php
id)}}">{{ $row->name }}
web.php
Route::get('/city/{id}/rooms/','SiteController#room')->name('room');
SiteController.php
public function room($id) {
$room = TotalCity::find($id)->location;
return view('frontend.pages.rooms', compact('room'));
}
rooms.blade.php
#foreach($room as $row)
<div class="room">
<img src="{{ asset(env('UPLOAD_PATH').'/' . $row['photoi1']) }}"/>
</div>
#endforeach
But this is not showing any rooms in any city while i have stored cities and rooms which comes under particular city in my database.
In the relationship method, you should mention foreign key and owner key as well,
for example in MyRoom.php:
public function location()
{
return $this->belongsTo(TotalCity::class, 'location_id', 'total_city_primary_key')->withTrashed();
}
you can read laravel documentioation for more detail.
foreignKey in TotalCity model is wrong :
public function location(){
return $this->hasMany(MyRoom::class, 'location_id')->withTrashed();
}
I strongly recommend you to change your model's names to City and Room. If you dont want to, make sure in both models you're connecting them to the correct table, you can achieve that using the $table variable in both models, like this:
$table = 'your_table_name';
This will make sure the table is connected right.
Also, you should make a few changes:
In your TotalCity model do this:
public function rooms()
{
return $this->hasMany(MyRoom::class , 'total_city_id')->withTrashed();
}
In your MyRoom model do this:
public function city()
{
return $this->belongsTo(TotalCity::class)->withTrashed();
}
In your SiteController do this:
public function room($id) {
$rooms = TotalCity::find($id)->rooms;
return view('frontend.pages.rooms', compact('rooms'));
}
In your View
#foreach($rooms as $room)
<h2>{{$room->name}}</h2>
<div class="room">
<img src="{{ asset(env('UPLOAD_PATH').'/' . $room['photoi1']) }}"/>
</div>
#endforeach

laravel eloquent repository query foreign key tables

hi i am using a custom repository and I am getting comfortable with querying one table to retrieve data like so:
public function getAll()
{
// get all logged in users projects order by project name asc and paginate 9 per page
return \Auth::user()->projects()->orderBy('project_name', 'ASC')->paginate(9);
}
and in my controller I simply call
public function __construct(ProjectRepositoryInterface $project) {
$this->project = $project;
}
public function index()
{
$projects = $this->project->getAll();
echo View::make('projects.index', compact('projects'));
}
and my view is as so:
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
{{ $project->project_name }}
#endforeach
#else
<p>No records, would you like to create some...</p>
#endif
{{ $projects->links; }}
#endif
However within my projects table I have a status_id and a client_id and I want to retrieve records of this these tables with the logged in user but I am not sure how to structure my query, does anyone have any guidance?
According to the laravel documentation, In your project model you can add the following function:
class Project extends Eloquent
{
public function clients()
{
return $this->hasMany(Client::class);
}
}
In your client model you can then add the inverse of the relationship with the function:
class Client extends Eloquent
{
public function project()
{
return $this->belongsTo(Project::class);
}
}
Then you can retrieve the data with a function like:
$clients = Project::find(1)->clients;

Categories