Got error 'Trying to get property 'id' of non-object' even dd function return it right - laravel

I have to display data from post table based on user. But, I always get error
Trying to get property 'id' of non-object
even though dd($user) and dd($post) return it right. dd($user) return 1st row, dd($post)return 1st row. When commenting all the 'dd' function , I got 'Trying to get property 'id' of non-object' at $post = post::find($user->id);. However when I dd($post->article_title, $post->id),I do get the data
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM) {
$user = User::find($RMM->id);
$post = post::find($user->id);
$post_data = array('title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
result of dd(post)
result of dd(user)

Be aware, when you dd() something it die at first iteration in foreach, error may occurs in another iterates, maybe id 1 is exists in user but 3 or 4 is not.

use something like this:
$RMM_details = Company::where('branch', 'RMM')->get();
$RMM_details->transform(function($RMM)use($user){
$user = User::find($RMM->id);
$post = post::find($user->id);
return [
'title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
];
});

It might be because
$post = post::find($user->id);
is returning null value at some stances.
Check if it is empty or not by using the function empty and try again.
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM) {
$user = User::find($RMM->id);
if(!empty($user->id){
$post = post::find($user->id);
}
$post_data = array('title' => $post->article_title,
'name' => $post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);

Related

Laravel 7 : Why I am Getting Only First Array? I want to Fetch All Category ID data

I am getting a issue while fetching array data in Laravel 7 here is my code
https://i.stack.imgur.com/IZbg6.png
and the result is : https://i.stack.imgur.com/ByKaV.png
It is fetching only one array data. I don't know where i am missing.
If anybody know the error, please help me to solve this issue.
Below is my code ======================================
$cat_id = $category->id;
$location = null;
$sites = \DB::select( 'SELECT id FROM sites WHERE category_id = ?', [ $category->id ]);
$all = [ ];
foreach( $sites as $s ) {
$all[ ] = $s->id;
}
$sites = $all;
$all_cat_id = implode(',', array_map('intval', $sites));
// echo "<pre>";
// print($all_cat_id);
// die();
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->where('id', [$all_cat_id])->paginate(10);
return view('browse-category', [ 'activeNav' => 'home',
'reviews' => $reviews,
'sites' => $sites,
'category' => $category,
'all_categories' => $all_categories,
'location' => $location
]);
$sites = Sites::withCount('reviews')->orderBy('reviews_count', 'desc')->whereIn('id', [$all_cat_id])->paginate(10);
You need to use whereIn() instead of where()
whereIn() checks column against array.

Laravel 8 multiple models to single view Error $address Not defined

I'm trying to create 2 rows in the DB using findOrNew() but when I use the ID from the Users model to create another model(Address) the programs returns undefined variable $address. I don't know if I'm using the correct approach or not. Bellow you can view my approach. Can you lead me to the right approach or where to find it?
2 models one view:
seeing what you have in your method is returning an undefined because it is not executing the findOrNew method correctly, check this link, maybe it will help you and this same
the second is that if you are passing the values by post everything will come to you in the $req parameter and only there then if you want to use the id you would have to access through $req->id if you send the data correctly
the third I see that in the view method you are passing 3 parameters when you should only pass two the first the name of the view the second the arrangement with the data that you will pass to the view
public function detail(Request $req)
{
$user = User::firstOrNew($req->id);
$user->user_type_id = 1;
$user->name = $req->name;
$user->last_name = $req->last_name;
$user->email = $req->email;
$user->password = Hash::make(Str::random(8));
$user->save();
$address = UserAddress::firstOrCreate(['user_id' => $req->id]); //or maybe $user->id
return view('user.detail', [
'user' => $user,
'adderss' => $address
]);
}
finally you may prefer to use the updateOrCreate method
public function detailV2(Request $req)
{
$user = User::updateOrCreate(
['id' => $req->id],
[
'user_type_id' => 1,
'name' => $req->name,
'last_name' => $req->last_name,
'email' => $req->email,
'password' => Hash::make(Str::random(8)),
]
);
$address = UserAddress::firstOrCreate(['user_id' => $user->id]);
return view('user.detail', [
'user' => $user,
'adderss' => $address
]);
}

Replace string by values from collection in Laravel

I am beginner ini Laravel. I have this code:
$value = "Szanowni Państwo,
Status został zmieniony.
<br/><br/>
Osoba odp.: {osoba_odpowiedzialna}<br/>";
$collection = collect(
(object) [
'osoba_odpowiedzialna' => $responsiblePerson,
'rodzaj' => data_get($term, 'termType.name'),
'klient' => data_get($term, 'client.name'),
'sprawa' => data_get($term, 'caseInstance.internal_signature'),
'status' => data_get($term, 'termStatus.name'),
'adres' => route('calendar.index')
]
);
in result $collection I have:
https://ibb.co/Kz18CJ1
I need replace my $value - values from $collection by key: osoba_odpowiedzialna, klient, rodzaj etc.
How can I make it?
Your question is not very clear, sorry, but I think what you want is this:
$replacedText = preg_replace('/{osoba_odpowiedzialna}/',
$collection['osoba_odpowiedzialna'], $value);
//this will yield (last line below)
//Osoba odp.: Łukasz Moderator
After your comments:
$collection->map(function($item, $key) use (&$value){ //$collection->each(.. should also be fine
$value = preg_replace('/{'.$key.'}/', $item, $value);
});

POST, Response and assertJson in phpunit testing

I have following test function to check the update data is correct or not.
It has no problem in updating.
My question is how to check the given parameters are correct after updated.
for example
if response.id == 1 and response.name = 'Mr.Smith'
assertcode = OK
else
assertcode = NG
public function user_update_info(){
$this->post('login',['email' => config('my-app.test_user'),
'password' => config('my-app.test_pass')]);
$response = $this->post('/update_info',[
'id' => 1,
'name' => 'Mr.Smith',
'post_code' => '142-4756',
'prefectural_code' => '15',
'address' => 'Merchat St.',]);
$response->assertStatus(200);
}
Assume your update_info route update User model.
Try below after your code,
$user = User::find(1);
static::assertTrue($user->id == 1 && $user->name = 'Mr.Smith');
To check if the response returns a json data you expect, you can use assertJson() method of the response object like so:
$response->assertJson([
'id' => 1,
'name' => 'Mr.Smith'
]);

Laravel 4 - Return the id of the current insert

I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;

Resources