Laravel get object attribute if object id is known - php

How do I get the value from a object if the ID is known?
So, I got the house id, in the house model there is an user_id for every house like:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use stdClass;
use App\Service\ChangesetService;
class HouseProfile extends Model
{
protected $guarded = ['id', 'user_id'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Every user got an address (string)
I need the address and I got the house id and I'm working in a blade file in Laravel 5.5

If I understand correctly:
#if($house->user)
{{ $house->user->address }}
#endif

You should never run queries of put too much logic in you Blade files. Instead you should pass variables to them.
In your controller
$house = HouseProfile::findOrFail($houseId);
return view('your.view.name', [
'house' => $house
]);
In your blade file you can use #IndianCoding response, so
#if($house->user)
{{ $house->user->address }}
#endif

Related

Cannot use laravel relationship property in blade view

EDIT: Problem solved by adding local key in the model relation.
Question:
I am trying to use a property from model relationship {{$item->items->item_name}}, but it says Attempt to read property "item_name" on null.
However, when I am trying to {{dd($item->items->item_name)}} it returns a string "Old Boots.
Why does it happen? The value is definitely there but I cant echo it...
UserItems table: id | user_id | item_id
UserItem Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserItem extends Model
{
use HasFactory;
public function items()
{
return $this->hasOne(Item::class, 'id');
}
}
Item table structure: id | item_name
Item Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
use HasFactory;
}
Controller function:
public function heroView() :View
{
return view('hero', [
'userItems' => UserItem::with('items')->where('user_id', Auth::id())->get()
]);
}
View:
<table>
#foreach ($userItems as $item)
<tr>
<td>{{$item->items->item_name}}</td>
</tr>
#endforeach
</table>
In view {{dd($item)}}:
You did not show your db, so I am just guessing with the data you shared here.
First of all if there is one item for each user item, you need to change items name to "item".
And there is something else too. You need to set inverse relationship to. I mean you have to add this to your item model. If it's a one to one relationship read this for learning about inverse relationships.
One to one inverse relationship(laravel document)
And at last, please remove "with" method. You do not need it laravel will figure out the relationship by itself.
Said all the possibilities. Hope to be helpful <3
most likely reason is that one of your userItem does not have an item.
dd appears to work because it stops on the first iteration of the loop, but your missing item could be missing from userItem 4 for instance.
Whenever I use an arrow twice when accessing a relationship, I always code defensively and put in a null-coalesce operator to catch the situation where a relation is missing.
So you could prove this with code like;
<table>
#foreach ($userItems as $item)
<tr>
<td>{{$item->items->item_name ?? "no item"}}</td>
</tr>
#endforeach
</table>
I finally made it work. There was local key missing in the model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserItem extends Model
{
use HasFactory;
public function items()
{
return $this->hasOne(Item::class, 'id', 'item_id');
}
}

laravel show database values in my blade front end foreign keys values

So I'm new to laravel and I'm trying to figure out a way to connect my database with my front end!
First this is the villa model for the table villas:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Villa extends Model
{
use HasFactory;
protected $fillable=[
"id", "title", "description", "price", "state", "status", "city_id", "seller_id", "payment_id", "created_at", "updated_at"
];
public function City()
{
return $this -> hasOne(City::class,'id','city_id');
}
public function Seller()
{
return $this -> hasOne(Seller::class,'id','seller_id');
}
public function Payment()
{
return $this -> hasOne(Payment::class,'id','payment_id');
}
}
this is the website controller : and here I'm trying to call the table
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Villa;
use App\Models\City;
use App\Models\VillaImg;
class WebsiteController extends Controller
{
public function index(){
$villas = DB::select('select * from villas');
return view('website',['villas'=>$villas]);
}
this is the website blade which I use this way to call the value but I don't know how to call a foreign key value , for example :
I have the foreign key city_id and I want the show the city name on my front end but don't know how
#foreach ($villas as $user)
{{old('name',$user->title )}}
#endforeach
#foreach ($villas as $user)
{{old('city',$user->I don't know what to write here)}}
#endforeach
Note: this is a code in a div that represents a villa block.
Also, I'm not sure if this is really the correct way to do so and I want to know if there's another efficient way to do that!
here's the route:
Route::get('/',[WebsiteController::class,'index'])->name('home.index');
use eloquent orm instead of db facade...
$villas = Villa::with(['City', 'Seller', 'Payment'])->get();
and then if u need any relation value:
#foreach ($villas as $villa)
{{ $villa->City->property }}
#endforeach

Call to undefined method stdClass::getModified()

Laravel v5.7.24
Laravel Auditing v8.0.4
PHP version 7.3.1
I've a specific problem related to package Laravel Auditing. Although I set the Model and everything like in documentation, the blade template is showing me an error Call to undefined method stdClass::getModified(). Thank you so much.
Here's my Model:
namespace App;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
class Post extends Model implements Auditable
{
use Searchable, \OwenIt\Auditing\Auditable;
protected $fillable = [...];
protected $auditExclude = [...];
public function user()
{
return $this->belongsTo('App\User');
}
}
Blade view:
<ul>
#forelse ($audits as $audit)
<li>
#foreach ($audit->getModified() as $attribute => $modified)
<ul>
<li>#lang('article.'.$audit->event.'.modified.'.$attribute, $modified)</li>
</ul>
#endforeach
</li>
#empty
<p>#lang('article.unavailable_audits')</p>
#endforelse
</ul>
Given that the error message (Call to undefined method stdClass::getModified()) refers to stdClass and not Audit, I'll take a wild guess and presume you're doing something like DB::table('audits')->where('auditable_type', Post::class)->get() to fetch the audits, which returns the results as POPO, not Audit instances.
Try this instead: Audit::where('auditable_type', Post::class)->get()

How to access this in my view

I am new with this laravel , I am using resource.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class BookController extends Controller
{
public function show($id)
{
$car = Cars::where('car_id',$id);
return view('book.view',compact('car'));
}
}
Here is my route.php
Route::resource('book','BookController');
Here is my view.blade.php
{{ $car->car_id }}
but it gives me error
Undefined property: Illuminate\Database\Eloquent\Builder::$car_id
How can I display the car_id ?
Thank you in advance.
If you are looking to fetch single record then do
$car = Cars::where('car_id', $id)->first();
return view('view.name', compact('car'))
and then access it in view like this :
{{$car->car_id}}
if you want to fetch many records do like this :
$cars = Cars::where('something', '=','otherthing')->get();
return view('view.name', compact('cars'));
and access it in view like this:
#foreach($cars as $car)
{{$car->car_id}}
#endforeach
You should follow naming conventions Never make your model name plural
try this
$car = Cars::where('car_id','=',$id)->get();
You can also get specific columns of all data in cars table using this:
$car=Cars::where('car_id',$id)->get(['car_id','car_name']);

Trying to get property of non-object in ;laravel array displaying

I have a laravel fetching controller like below,
public function fetchbywhere()
{
$result=User::find(2);
return View::make('fetchbywhere')->with('resultrow',$result);
}
My Model file of User.php like,
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
and my routes.php file ,
Route::get('select-by-where',array('as'=>'select_by_where','uses'=>'Test#fetchbywhere'));
and my view file named fetchbywhere.blade.php,
<title>Fetch by Where clouse</title>
<h2>Users - Where clouse</h2>
#foreach($resultrow as $data)
<ul>
<li>{{$data->name}}</li>
</ul>
#endforeach
my database have fields like
id|name|email|age|created_at|updated_at
am getting error like Trying to get property of non-object (View: E:\wamp\www\new_laravel\app\views\fetchbywhere.blade.php)
anybody please give me a solution. t
thanks
You are using User::find(2) this returns a single instance of User with id = 2. Or even null if it doesn't exist. In your view you are iterating over $resultrow as if it where a collection and not a single model.
I believe what you actually want to do is something like this:
$result=User::where('some-column', 'operator', 'some-value')->get();
return View::make('fetchbywhere')->with('resultrow',$result);
So an example could be...
$result=User::where('age', '>', '18')->get();
return View::make('fetchbywhere')->with('resultrow',$result);
...to get everybody over 18
Also its "where clause" not clouse ;)
Update
The actual use for the find method is to get only one object with the passed id (primary key in the database). It doesn't return a collection (list) because there no way it could find multiple rows with the same id, since the primary key is unique.
If you only want one user (by a specific id) you have to change your view to directly access the model
<title>Fetch by Where clouse</title>
<h2>Users - Where clouse</h2>
{{ $resultrow->name }}

Categories