-2

I am trying to get the property $seen->seen inside of a for-each loop but I am getting:

"Attempt to read property "seen" on null"

When I do it outside of the for-each loop it works fine

public function getromes(Request $request)
{
    $user = Auth::id();
    $romes = Rome::where('room', $request->id)->get();
    $romeids = $romes->pluck('uuid');

    // $seen = Seen::where('message', 'IcHshOP2V')
    //    ->where('user', $user)
    //    ->first();
    // $wasseen = $seen->seen;
    
    foreach ($romeids as $uuid) {
        $seen = Seen::where('message', $uuid)
            ->where('user', $user)
            ->first();

        $wasseen = $seen->seen;

        if ($seen->seen === 0) {
            $seen->seen = 1;
            $seen->seen_at = Carbon::now();
            $seen->save();
        }
    }

    return response()->json([
        'message' => 'Getting posts was successful',
        'romes' => $romes,
        'wasseen' => $wasseen
    ], 200);
}

Rome model

class Rome extends Model
{
    use HasFactory;

    protected $fillable = [
        'sender',
        'room',
        'msgtext',
        'uuid',
        'edited',
        'files',
        'images',
        'seen'
    ];
}

Seen Model

class Seen extends Model
{
    use HasFactory;

    protected $fillable = [
        'message',
        'user',
        'seen',
        'seen_at'
    ];
}



*> var_dump($seen) inside for-each loop looks like this*



> object(Illuminate\Database\Eloquent\Collection)#309 (2) {  
> ["items":protected]=>   array(0) {   }  
> ["escapeWhenCastingToString":protected]=>   bool(false) }
> object(Illuminate\Database\Eloquent\Collection)#310 (2) {  
> ["items":protected]=>   array(0) {   }  
> ["escapeWhenCastingToString":protected]=>   bool(false) }
> object(Illuminate\Database\Eloquent\Collection)#1048 (2) {  
> ["items":protected]=>   array(0) {   }  
> ["escapeWhenCastingToString":protected]=>   bool(false) }
> object(Illuminate\Database\Eloquent\Collection)#313 (2) {  
> ["items":protected]=>   array(0) {   }  
> ["escapeWhenCastingToString":protected]=>   bool(false) }
> object(Illuminate\Database\Eloquent\Collection)#315 (2) {  
> ["items":protected]=>   array(0) {   }  
> ["escapeWhenCastingToString":protected]=>   bool(false) }
> object(Illuminate\Database\Eloquent\Collection)#314 (2) {  
> ["items":protected]=>   array(0) {   }  
> ["escapeWhenCastingToString":protected]=>   bool(false) }
> object(Illuminate\Database\Eloquent\Collection)#1274 (2) {  
> ["items":protected]=>   array(1) {
>     [0]=>
>     object(App\Models\Seen)#1275 (30) {
>       ["connection":protected]=>
>       string(5) "mysql"
>       ["table":protected]=>
>       string(5) "seens"
>       ["primaryKey":protected]=>
>       string(2) "id"
>       ["keyType":protected]=>
>       string(3) "int"
>       ["incrementing"]=>
>       bool(true)
>       ["with":protected]=>
>       array(0) {
>       }
>       ["withCount":protected]=>
>       array(0) {
>       }
>       ["preventsLazyLoading"]=>
>       bool(false)
>       ["perPage":protected]=>
>       int(15)
>       ["exists"]=>
>       bool(true)
>       ["wasRecentlyCreated"]=>
>       bool(false)
>       ["escapeWhenCastingToString":protected]=>
>       bool(false)
>       ["attributes":protected]=>
>       array(7) {
>         ["id"]=>
>         int(3)
>         ["message"]=>
>         string(9) "IcHshOP2V"
>         ["user"]=>
>         string(1) "3"
>         ["seen"]=>
>         int(0)
>         ["seen_at"]=>
>         string(1) "0"
>         ["created_at"]=>
>         string(19) "2023-03-30 15:18:59"
>         ["updated_at"]=>
>         string(19) "2023-03-30 15:18:59"
>       }
>       ["original":protected]=>
>       array(7) {
>         ["id"]=>
>         int(3)
>         ["message"]=>
>         string(9) "IcHshOP2V"
>         ["user"]=>
>         string(1) "3"
>         ["seen"]=>
>         int(0)
>         ["seen_at"]=>
>         string(1) "0"
>         ["created_at"]=>
>         string(19) "2023-03-30 15:18:59"
>         ["updated_at"]=>
>         string(19) "2023-03-30 15:18:59"
>       }
>       ["changes":protected]=>
>       array(0) {
>       }
>       ["casts":protected]=>
>       array(0) {
>       }
>       ["classCastCache":protected]=>
>       array(0) {
>       }
>       ["attributeCastCache":protected]=>
>       array(0) {
>       }
>       ["dates":protected]=>
>       array(0) {
>       }
>       ["dateFormat":protected]=>
>       NULL
>       ["appends":protected]=>
>       array(0) {
>       }
>       ["dispatchesEvents":protected]=>
>       array(0) {
>       }
>       ["observables":protected]=>
>       array(0) {
>       }
>       ["relations":protected]=>
>       array(0) {
>       }
>       ["touches":protected]=>
>       array(0) {
>       }
>       ["timestamps"]=>
>       bool(true)
>       ["hidden":protected]=>
>       array(0) {
>       }
>       ["visible":protected]=>
>       array(0) {
>       }
>       ["fillable":protected]=>
>       array(4) {
>         [0]=>
>         string(7) "message"
>         [1]=>
>         string(4) "user"
>         [2]=>
>         string(4) "seen"
>         [3]=>
>         string(7) "seen_at"
>       }
>       ["guarded":protected]=>
>       array(1) {
>         [0]=>
>         string(1) "*"
>       }
>     }   }   ["escapeWhenCastingToString":protected]=>   bool(false) } {"message":"Getting posts  was
> successful","romes":[{"id":1,"sender":7,"room":"1","msgtext":"agfdasfasdf","uuid":"2tAwioIIu","edited":0,"files":null,"images":null,"seen":null,"participants":"\"ALL\"","created_at":"2023-03-30T15:00:40.000000Z","updated_at":"2023-03-30T15:00:40.000000Z"},{"id":2,"sender":3,"room":"1","msgtext":"sdfgfdsg","uuid":"ic91IRrqX","edited":0,"files":null,"images":null,"seen":null,"participants":"\"ALL\"","created_at":"2023-03-30T15:00:43.000000Z","updated_at":"2023-03-30T15:00:43.000000Z"},{"id":3,"sender":5,"room":"1","msgtext":"zxcvxcv","uuid":"x5qXAtRot","edited":0,"files":null,"images":null,"seen":null,"participants":"\"ALL\"","created_at":"2023-03-30T15:01:56.000000Z","updated_at":"2023-03-30T15:01:56.000000Z"},{"id":4,"sender":3,"room":"1","msgtext":"fsadfasdfasdf","uuid":"MJD6jjfBU","edited":0,"files":null,"images":null,"seen":null,"participants":"\"ALL\"","created_at":"2023-03-30T15:13:34.000000Z","updated_at":"2023-03-30T15:13:34.000000Z"},{"id":5,"sender":3,"room":"1","msgtext":"fsadfasdfasdf","uuid":"fJc4lEHji","edited":0,"files":null,"images":null,"seen":null,"participants":"\"ALL\"","created_at":"2023-03-30T15:14:12.000000Z","updated_at":"2023-03-30T15:14:12.000000Z"},{"id":6,"sender":3,"room":"1","msgtext":"dxzvfvcxvxcv","uuid":"VVEQHNSm5","edited":0,"files":null,"images":null,"seen":null,"participants":"\"ALL\"","created_at":"2023-03-30T15:14:33.000000Z","updated_at":"2023-03-30T15:14:33.000000Z"},{"id":7,"sender":3,"room":"1","msgtext":"vcmbnxcvn","uuid":"IcHshOP2V","edited":0,"files":null,"images":null,"seen":null,"participants":"\"ALL\"","created_at":"2023-03-30T15:18:59.000000Z","updated_at":"2023-03-30T15:18:59.000000Z"}]}
eddbreuer
  • 35
  • 1
  • 10
  • 1
    Seen::where() appears to be returning null for some value of $uuid. I suggest you add var_dump($uuid) and var_dump($seen) to identify which is the problem value – Rob Eyre Mar 31 '23 at 13:49
  • 2
    @RobEyre not `Seen::where()` but `Seen::first()`, the issue is that, whatever condition the author is adding, it is not finding a result back when it executs `->first()` – matiaslauriti Mar 31 '23 at 13:50
  • Good spot - thanks for identifying. The var_dump() should help though – Rob Eyre Mar 31 '23 at 13:54
  • Thanks, but... var_dump($uuid) returns 'string(9) "x5qXAtRot" NULL', – eddbreuer Mar 31 '23 at 14:32
  • A simple `if ($seen) { ... }` around all of the code where you access `$seen-> ...` should handle this. `$seen` is `null`, which `->first()` can return, so you need to handle that case, which you currently are not doing. You're assuming that `->first()` is returning a record on each iteration of `foreach ($romeids as $uuid) { ... }`, but that is not the case, and your error is telling you exactly that. – Tim Lewis Mar 31 '23 at 15:08
  • 1
    @mankowitz The downvotes are from the error message being self-evident, and the lack of debugging attempts. The error very clearly says that accessing the property "seen" (`->seen`) is happening on a `null` variable (`$seen`, since the only spot `->seen` is happening is there, and the line below). If the asker had done any debugging, like `var_dump($seen)`, they'd see that an instance is `null`, and could then fix it. Also, there are _hundreds_ of questions on SO with this exact error; they didn't look any of them up before asking this question. The content is fine, the process is downvotable. – Tim Lewis Mar 31 '23 at 20:01
  • @TimLewis - ok, that's fair. – mankowitz Apr 02 '23 at 00:44
  • OK, mankovitz and TimLewis Thanks for you trying to tell me that I am doing things wrong. I get that. It is logical that if I can get $seen on the outside of for-each loop I should get it inside. I am not getting it. var_dump($seen) didn't tell me how to fix it or where. Usually, I see people asking questions here and good people respond with solutions and something to learn from. I didn't learn anything from asking this question other than that I don't know what I am doing wrong. Does anyone have a solution to my problem? – eddbreuer Apr 03 '23 at 14:31
  • You need to realize you're doing a loop; each time the loop runs `$seen` **will be different**, and in one of those loops, `$seen` is `null`, and `null->seen` is obviously not valid code. You need to handle this. `var_dump($seen)` is debugging code, and can show you when `$seen` is `null`, or an Object, etc. The end case is that you need to handle this; your error is telling you that `$seen` is `null` during one of your loops, and has to be handled, like adding an `if ($seen) { $wasseen = $seen->seen; ... }` (... being the rest of the code). – Tim Lewis Apr 03 '23 at 16:21
  • @TimLewis. Thank you so much. It finally got into my head what you meant to say the first time. Thank you! – eddbreuer Apr 03 '23 at 16:43
  • Excellent; and apologies if anything we said comes across as condescending or dismissive; that's not what we're aiming for at all. You've got the right idea now with your working code; being aware of what is "safe" or "unsafe" code (i.e. assuming `->first()` cannot return `null`), etc.) comes with trial and error, especially with Vendor Code (Laravel framework). You could also use something like `firstOrFail()` if you _need_ something to exist, or `firstOrCreate()` if you want to create something if it doesn't, etc etc. Happy coding! – Tim Lewis Apr 03 '23 at 16:48

1 Answers1

1

Thanks, Tim Lewis

This is the working code!

public function getromes(Request $request)
{
    $user = Auth::id();
    $romes = Rome::where('room', $request->id)->get();
    foreach($romes as $rome){
        $seen = Seen::where('message', $rome->romeid)->where('user', $user)->first();
        if($seen && !$seen->seen){
            $seen->seen = 1;
            $seen->seen_at = Carbon::now();
            $seen->save();
        }
    }
    return response()->json([
        'message' => 'Getting posts was successful',
        'romes' => $romes,
    ], 200);
}
Mano Mahe
  • 84
  • 1
  • 17
eddbreuer
  • 35
  • 1
  • 10
  • Some improvements, you can delete the `$romeids` variable, and just do `foreach($romes as $rome)`, then `$seen = Seen::where('message', $rome->romeid)`. Also, `if ($seen) { if ($seen->seen === 0) { ... } }`, can be rewritten as `if ($seen && !$seen->seen) { ... }` (or similar); no need to nest an `if` without an `else` or `else if` branch. – Tim Lewis Apr 03 '23 at 16:56