Laravel displaying many to many relationship items - php

I have set up a many to many relationship in Laravel and have the database table populated with data. The relationship setup looks like this...
users.php
---------
public function houses()
{
return $this->belongsToMany('App\House')
->withTimestamps();
}
house.php
---------
public function users()
{
return $this->belongsToMany('App\User')
->withTimestamps();
}
In my /house/show.blade.php I am trying to display the saved connections like this...
$houses = House::with('App\User')->all();
foreach ($houses as $house) {
echo 'Found House';
}
It is giving me an error saying that $houses can not be found. Where am I going wrong?

You should indicate the relationship in the with method like this :
$houses = House::with('users')->get();
And one more thing it's better to get houses in the controller and pass them to the view :
$houses = House::with('users')->get();
return view('someView')->withHouses($houses);
And in the view do it like this :
#foreach ($houses as $house)
{{ $house->addres }}
#endforeach
To get only the houses taht has the users try this :
$houses = House::has('users')->get();
And to add some conditions on the users you can do it like this :
$houses = House::whereHas('users', function ($query) {
$query->where('name', 'some user name'); // to add some conditions on the user :)
})->get();

You should try this:
$houses = House::with('users')->get();
foreach ($houses as $house) {
echo 'Found House';
}
OR
In controller:
use House;
$houses = House::with('users')->get();
return view('someView',compact('houses'));
In Blade file:
#foreach ($houses as $house)
{{ $house->name }}
#endforeach

Related

Comparing 2 tables in Laravel

Comparing to tables in Laravel. I have this code in my class (model):
public function table1() {
return $this->hasOne(table1Class::class, 'type', 'bms_id');
}
public function table2() {
return $this->belongsTo(table2Class::class, 'bms_id', 'type');
}
The controller, has something like this:
$type =
DB::table('table2')
->join('table1', 'table1.col_id','table1.col_name')
->select('table2.*', 'table1.*')
->get();
$dataMerge = $dataMerge->merge($type);
In the view, I have:
#foreach($data as $item)
{{$item->type==120}} //this works, no problem
{{$item->col_name}} //this produces nothing!
#endforeach
As you can see, the code stops working when referencing the col_name, any suggestions?
Thanks in advance!

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')); }

How to add pagination to relation in laravel 7 controller?

How can I add pagination to model relation in my controller? Here's my case :
public function show($movie) {
$movie = Movie::find($movie);
$episodes = $movie->episodes;
$genre = $movie->genre;
return view('layout.detailMovie', compact('movie', 'episodes', 'genre'));
}
I want to add pagination for the $episodes. Where do I have to put the "->paginate()" code?
public function show($movie) {
$movies = Movie::with('episodes', 'genre')->where('movie', $movie)->paginate(3);
return view('layout.detailMovie', compact('movies'));
}
In Blade
{{ $products->links() }} OR {{ $products->render() }}
You can fetch data in blade like
foreach($movies as $movie) {}
//your code
}
foreach($movies->episodes as $episodes) {}
//your code
}
foreach($movies->genre as $genre) {}
//your code
}
try this :
Movie::find($movie)->with('episodes')->paginate(3);
or:
$reports = User::find($user->id)
->reports()
->orderBy('created_at', 'DESC')
->paginate($paginate);
return $reports;
if that doesnt work look at this :
How to paginate a "has many" relationship that is ordered?

laravel no result from my query

I'm a beginner in Laravel
public function allorders($param1){
$customerss=Customer::where('mobile_number',$param1)->first();
$customer_id1=$customerss->id;
$orderss= Order::where('customer_id',$customer_id1);
return view('admin.allorders')->with('orderss', $orderss);
}
and i have the view admin.allorders
#foreach ($orderss as $tag)
<span class="label label-primary">{{ $tag['customer_id']}}</span>
#endforeach
I'm sure the $orderss is having data but it's not shown in the view.
You need to add get() to execute the query:
$orderss = Order::where('customer_id', $customer_id1)->get();
Also, you could use relationships instead of this:
$customerss=Customer::where('mobile_number',$param1)->first();
$customer_id1=$customerss->id;
$orderss= Order::where('customer_id',$customer_id1);
You could do the same with just one query:
$orderss = Order::whereHas('customer', function($q) use($param1) {
$q->where('mobile_number', $param1);
})->get();
To make it work, define this relationship in the Order model:
public function customer()
{
return $this->belongsTo(Customer::class);
}

Laravel belongsTo returns, put can't save in var

I'm trying to get the username by a item with belongsTo.
I have this in my Item model:
public function user()
{
return $this->belongsTo('User', 'user_id', 'id');
}
And this in my controller:
$user = $item->user->username;
But I get:
Trying to get property of non-object
And when I do:
return $item->user->username;
In my controller it works.
What can be wrong?
Controller/Model: http://pastebin.com/qpAh8eFd
You have following function in your controller:
public function index($type)
{
$items = $this->item->where('type', '=', $type)->get();
foreach($items as $item):
$user = $item->user->username;
endforeach;
return View::make('items.index', ['items' => $items, 'user' => $user]);
}
You don't need to do a foreach look in the controller and whatever you are doing you are doing it wrong, instead make your index function like this:
public function index($type)
{
$items = $this->item->where('type', '=', $type)->get();
return View::make('items.index', ['items' => $items]);
}
Pass only $items to your items/index.blade.php view. You may do a foreach loop in your view if needed and within each iteration you may access the user related to the item using something like this:
#foreach($items as $item)
{{ $item->user->uername }}
#endforeach
You may get Trying to get property of non-object error message because each $item may don't have a related user. So, make sure each $item has a related user. You can also, use following to get items with user:
$items = $this->item->with('user')->where('type', '=', $type)->get();
return View::make('items.index', ['items' => $items]);
In your view you may check if the item has a related user:
#foreach($items as $item)
#if($item->user)
{{ $item->user->uername }}
#endif
#endforeach

Categories