Debarun Pal
Debarun Pal

Reputation: 113

How to access property of an object in Laravel PHP?

I am having 2 methods. In one of the method I am making a call to database, a pure and simple one Document::findOrFail($data->id). But this is always returning me null although a record is already persisted. Any idea how to get this simple thing sorted?

public function lockExport(Request $request){

    $document = Document::create([
     'user_id' => $this->userId(),
     'extension' => $extension,
     'name' => $filename,
     'file_path' => $filepath,
     'size' => File::size($filepath . $filename),
     'received_at' => Carbon::now()->format('Y-m-d')
   ]);
   $isAttachment = false;

   Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);

   return $this->downloadlockExport($token);
}
public function downloadlockExport($token)
{
    try {

        $data = (object) Cache::get($token);
        // dd I get the full $data as object

        $document = Document::findOrFail($data->id);

        // undefined. Above query did not execute. 
        // Thus, below query failed
        $document->update(['downloads' => $document->downloads + 1]);

        $content = Crypt::decrypt(File::get($data->file));

        return response()->make($content, 200, array(
            'Content-Disposition' => 'attachment; filename="' . basename($data->file) . '"'
        ));

    } catch (\Exception $e) {
        \App::abort(404);
    }
}

Upvotes: 1

Views: 176

Answers (1)

Zollie
Zollie

Reputation: 1211

What you probably would like to do is:

public function lockExport(Request $request){

    $document = Document::create([
     'user_id' => $this->userId(),
     'extension' => $extension,
     'name' => $filename,
     'file_path' => $filepath,
     'size' => File::size($filepath . $filename),
     'received_at' => Carbon::now()->format('Y-m-d')
   ]);
   $isAttachment = false;

   $token = 'mytoken';
   Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);

   return $this->downloadlockExport($token);
}

This way you will get your $token in your called function and you will get the $data correctly as I see.

And in the downloadlockExport() function you will have the ID like this:

$document = Document::findOrFail($data->mytoken['id']);

or you can use:

$document = Document::findOrFail($data->$token['id']);

similar with getting the File value:

$content = Crypt::decrypt(File::get($data->$token['file']));

Upvotes: 1

Related Questions