I have a web application where my users can upload text documents and emails into what I call Streams. A stream is like a "stack", that holds all emails / documents.

My users can then add fields to the stream, and field_rules. This means, that every time a new document or email is added, the text content of the document/email, will be parsed according to the rules, and then the final parsing result is then stored in the database.

My current code works, to some degree, however, it feels a bit "hackish" as well as not very "Laravel like".

My progress so far

Whenever a new document (or email) is added, it will be handled by a queue:

public function handle(DocumentHandlingFinished $event)
    $stream = Stream::find($event->document->stream_id);
    $ParsingRules = new ApplyParsingRules($stream, $event->document);


    return true;

OK, so in above I start off by getting the "Stream" that the document was uploaded to.

Then I instanciate the ParsingRule class, that will perform the various rules on the content of the document.

Finally, I save the parsed results to the database.

Below you can see my ApplyParsingRule class:

public function __construct(Stream $stream, Document $document)
    $this->data = $document;
    $this->content = $document->content;
    $this->stream = $stream;
    $this->fields = $this->stream->documentfields()->with('rules')->get();

//Iterate through each rule and parse through the content.
public function parse() : object
    $content = $this->content;
    $results = collect([]);
    foreach ($this->fields as $field) {
        foreach ($field->rules as $fieldrule) {

            $content = doSomething($content); //Minified for simplicity.
            $results[] = [
                'field_rule_id' => $fieldrule->id,
                'content' => $content


    return $results;

Now as you can see in my handle message, I call the parse() function and then saves the results:


In my Document model, I have the storeResults() function:


//Persist the parsed content to the database.
public function storeResults(object $results) : object
    //If the document was already parsed before, delete old records.
    if ($this->results->count() > 0) {

    //Use ->last() because we only want to insert the last parsed text result.
    return $this->results()->create($results->last());

So above flow works as long as the $results array contains information.

I was wondering if above code can be refactored / improved even further?

Another concern I have is, If the $results array from the ApplyParsingRule class is empty, then the create() method will fail.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.