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

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 }}

Related

laravel how to get use with relation in blade after login

I am using Laravel 8 and the User model has relation with model UserProfile
as following
class User extends Authenticatable
{
use LaratrustUserTrait;
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
.
.
.
public function profile(){
return $this->hasOne(UserProfile::class,'user_id');
}
}
when i create a new user i directly do login for him and redirect him to dashboard
as following
Auth::login($user, true);
return $this->sendSuccessResponse();
but my question is how i can use user data with it's userProfile relation in blade or controller
I tried to use the following code in blade
<img src="{{Auth::user()->profile->image}}" id="profile-img" alt="">
but i get the following error message
Attempt to read property "image" on null
Your profile relationship is either malformed or missing.
This error means that you are trying to get the property image on a value of null.
That's because Auth::user()->profile returns null, then Auth::user()->profile->image is like writing (null)->image.
This can be caused by several things:
Missing data in the database
Wrong columns name
Wrong tables name
The easiest thing to bypass this error would be to only display the image when this relationship isn't null:
#if(Auth::user()->profile !== null)
<img src="{{Auth::user()->profile->image}}" id="profile-img" alt="">
#endif
However, it would be better to understand why it's null, at least to avoid further problems in your project.
Apply these changes in your User model. I think it will work for you.
User Model
class User extends Authenticatable
{
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = ['profile'];
/**
* Get the user profile.
*/
public function profile()
{
return $this->hasOne(UserProfile::class);
}
}

Incompatible method with the override of setKeysForSaveQuery() on Laravel 8

We created three tables called 'users', 'corso', 'iscrizione' which is a middle table between users and corso, it has two attributes that are PK/FK. We successfully built the methods to create/update/read/delete rows inside 'corso' and we populated manually 'users'. We are trying to realize a create method for iscrizione but when we try to test it on Postman it gives us an error: 🧨 Illegal offset type
We learned that Eloquent doesn't support composite keys (which is a shame) and the only way to bypass this limit is to override the method setKeysForSaveQuery() from Eloquent inside the model of our table.
Sadly it gives us this error:
Method 'App\Models\Iscrizione::setKeysForSaveQuery()' is not compatible with method 'Illuminate\Database\Eloquent\Model::setKeysForSaveQuery()'.intelephense(1038)
Iscrizione Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class Iscrizione extends Model
{
use HasFactory;
protected $hidden = ['idCorso', 'idUtente'];
protected $table = 'iscrizione';
protected function setKeysForSaveQuery(Builder $query){
return $query->where('idCorso', $this->getAttribute('idCorso'))
->where('idUtente', $this->getAttribute('idUtente'));
}
}
You need to make it match change the below code
protected function setKeysForSaveQuery(Builder $query){
to
protected function setKeysForSaveQuery($query){

Getting wrong data from database even if I am fetching something different in laravel api

Hello guys I am working on a laravel project for making api for passing the database value in json format but the problem is I have a users table in this table 2 ids 1 is primary key and second is business _id I want to get data according to business_id but it's getting data by id please help me how to solve this issue.
Here is my model code
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
}
Here is my Controller Code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\user;
class GetController extends Controller
{
public function databybusinessid($business _id){
$users = new user();
$users = user::find($business _id);
return response()->json($users);
}
}
Thank you so much
You are using user::find($business _id)
find() method will automatically search by the primary key but none is defined in your model and Eloquent can't decide which one to pick from your table. Therefore, you should explicitly set your primary key in your model by adding the following line.
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
If in doubt, you can also fetch database record by a specific column using where
$users = user::where('business_id', '=', $business _id)->get()
Laravel documentation about Eloquent ORM
https://laravel.com/docs/5.8/eloquent
find() Retrieve a model by its primary key..
So you have to use your code as:
$users = user::where('business_id',$business_id)->first();
// Notice first() Retrieve the first model matching the query constraints...
Or you can change your primary code in model
namespace App;
use Illuminate\Database\Eloquent\Model;
class user extends Model
{
protected $table = 'business';
protected $primaryKey = 'business_id';
}
find() works only on primary key. you need to use where instead.
or you can define business_id as primary key in your User model.
protected $primaryKey = 'business_id';
public function databybusinessid($business _id){
$users = new user();
$users = user::where('business_id',$business _id)->first();
return response()->json($users);
}

How to Inverse the Eloquent Has One and Has Many Through (laravel 5.8)?

I have three relational table attached below.
https://drive.google.com/file/d/1q1kdURIwFXxHb2MgdRyBkE1e3DMug7r-/view?usp=sharing
I have also three separate models where defined relation among all of my table's.I can read the City Model's information from Country model using hasManyThrough() relation But cannot read the Country information from City model. I have tried to retrieve City model's using ``hasManyThrough``` but didn't get result (attached as commented country method ). Please read my model and it's relational method here..
Is there someone to help me for getting City model's information using Eloquent method hasManyThrough / hasManyThrough or using inverse of hasManyThrough / hasManyThrough ?
01.
<?php
namespace App\Hrm;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Country extends Model
{
//use SoftDeletes;
protected $fillable = ['name','description','status'];
public function districts(){
return $this->hasMany(District::class);
}
public function cities(){
return $this->hasManyThrough(City::class,District::class);
}
}
02.
<?php
namespace App\Hrm;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class District extends Model
{
//use SoftDeletes;
protected $fillable = ['country_id','name','description','status'];
public function country(){
return $this->belongsTo(Country::class);
}
public function cities(){
return $this->hasMany(City::class);
}
}
3.
namespace App\Hrm;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class City extends Model
{
//use SoftDeletes;
protected $fillable = ['district_id','name','description','status'];
public function district(){
return $this->belongsTo(District::class);
}
// public function country(){
// return $this->hasOneThrough(Country::class, District::class);
// }
Doesn't look like there is a native way to define the inverse of a "hasManyThrough" relationship yet in Laravel. There have been a few issues opened on github to request it, but they were closed.
You could use the staudenmeir/belongs-to-through package if you don't mind installing a third-party package for this functionality. Then you should be able to define a belongsToThrough relationship like this:
class City extends Model
{
use \Znck\Eloquent\Traits\BelongsToThrough;
public function country() {
return $this->belongsToThrough(Country::class, District::class);
}
}
Why can't use parent method?
$city = City::find(1);
$country = $city->district->country();
i just had a similar situation i was able to accomplish a belongsToThrough with hasOneThrough
public function country()
{
return $this->hasOneThrough(
Country::class, // model we are trying to get
District::class, // model we have an _id to
'id', // WHERE `district`.`id` = `city`.`district_id`
'id', // `countries`.`id`
'district_id', // local column relation to our through class
'country_id' // `district`.`country_id`
);
}
what this should generate is
SELECT * FROM `countries`
INNER JOIN `districts`
ON `districts`.`country_id` = `countries`.`id`
WHERE `districts`.`id` = ?
-- ? == city.district_id
Database structure:
City:
id: increments
district_id: integer
...
Country:
id: increments
...
District:
id: increments
country_id: integer
...
we can then do $city->country
note: i have not fully tested this but with the testing that i have done it 'works'
Edit: i originally thought that i needed to leave the localKey
parameter null otherwise the relation wont work. it turns out i didnt
fully understand what that column was doing and that was wrong. That
key is the local column that relates to our through column (unless i
still have more to learn/figure out), when left the value as null, it
would use the local id column which a. is the wrong value, b. can also
be out of range (which is how i discovered it was using the wrong
value)
in my testing i only had two rows, both with the same relations. what
i didnt realize though was that on the "through table" both row 1 and
2 and the same related (relation where are trying to reach) so i didnt
notice the issue right away. hopefully now its all working

Laravel relationship returning null

I'm trying to fetch database data through a model relationship in Laravel.
I've set up one model, like this:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Userskeywords extends Eloquent {
public function relatedKeywords()
{
return $this->hasOne('Keywords', 'id', 'keywordId');
}
}
?>
And the other model is just a normal model. In the database they look like this:
Keywords
UsersKeywords
However, when I run UsersKeywords::with('relatedKeywords')->get() it returns NULLfor related_keywords. This happens when the following code is executed. What am I doing wrong?
$keywords = Userskeywords::where('user', '=', $id)->get();
$keywords->load('relatedKeywords');
return Response::json($keywords);
Your relation is called relatedKeywords so you need to access related object with
$object->relatedKeywords
instead of
$object->related_keywords

Categories