Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ticked's avatar

Laravel and Mailgun

Hello...

I using Mailgun API to build a dashboard where subscribers of a newsletter can see their subscription status, following Mailgun's code examples I have:

On my controller I have the following:

public function newsletter(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        return response()->json($result, 200, array());
}

When calling the above method I have on my browser the following JSON response, which I believe is great!

{
"http_response_body": {
"items": [
{
"address": "test@testdomain.com",
"name": "Patric Mongan",
"subscribed": false,
"vars": {}
}
],
"total_count": 1
},
"http_response_code": 200
}

I want to pass the above data to a view and echo the name and email address, how do I do that?

I have tried:

public function newsletter(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        return response()->json($result, 200, array());
    //also
    //return view ('status')->with($result);
    //also
    //var_dump(json_decode(json_encode($result),true));
}

Nothing works, any advice would be much appreciated, please consider I'm just starting with all this Laravel coding... Thank you!.

0 likes
17 replies
bobbybouwmann's avatar

If you want a view you can do this

return view('status', compact('result'));

// Or
return view('status')->with(['result' => $result]);

// Or even
return view('status')->withResult($result);
Ticked's avatar

Hi, Thanks bobbybouwmann,

I have tried... no luck...

return view('status', compact('result'));

And on my view:

{{ $result->address }}

Also

{{ $result['address'] }}

I get:

Undefined property: stdClass::$address
bobbybouwmann's avatar

Try this first to see what kind of data you have

$result = $mgClient->get("lists/$listAddress/members", array(
    'address' => $user->email
));

dd($result);

return view('status', compact('result'));               
BENderIsGr8te's avatar

It looks like you are getting raw JSON back from your initial request. In PHP JSON is nothing more than a string of text. You would need to convert it to a native PHP dataType if you wanted to be able to access it. I would take your response, do a json_decode which turns your JSON string into a PHP Array, then you can access it using the Array keys as you tried above.

$result = $mgClient->get("lists/{$listAddress}/members", array(
            'address' => $user->email
        ));
    
$result = json_decode($result); // this is now a Native PHP Array

It's also important to note the following

return response()->json(['key' => 'val']);

return response(['key' => 'val']); // Same as previous line. Response converts to JSON natively in Laravel

The reason json_decode makes a difference is because you are passing native JSON to your response(). The Response (and json()) are looking for an array to encode into JSON. So your problem should be solved by decoding the JSON to an array and then passing the array to your view (or returning the array into your response which will then be re-cast as JSON).

Ticked's avatar

Hey BENderIsGr8te,

I have try to implement your advice, thank so much, it is nearly there now...

Now the browser shows this:

array (size=2)
      'items' => 
        array (size=1)
          0 => 
            array (size=4)
              ...
      'total_count' => int 1
  'http_response_code' => int 200

have a look...

The controller

public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        $result2 = (var_dump(json_decode(json_encode($result),true)));

        return view ('account.subscriptions.newsletter.index', compact('result2'));

    }

The view

@extends('account.layouts.master')

@section('content')

    <div class="page-header">
        <h1>The Mayfair Magazine | <small>Account / Subscriptions</small></h1>
    </div>


    <div class="row">
        <div class="col-md-12 col-lg-8 col-lg-offset-2">

        <h3>Newsletter</h3>
        <hr>
        <p>Mailgun says:</p>

            {{ $result2['address'] }}

        </div>
    </div>

@endsection
Ticked's avatar

More clearly...

When calling this:

public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        $result = (var_dump(json_decode(json_encode($result),true)));

        //return view ('account.subscriptions.newsletter.index', compact('result'));

        echo $result['address'];

    }

On the browser I get an empty array, am I correct?

array (size=2)
  'http_response_body' => 
    array (size=2)
      'items' => 
        array (size=1)
          0 => 
            array (size=4)
              ...
      'total_count' => int 1
  'http_response_code' => int 200
BENderIsGr8te's avatar

json_decode takes a JSON string and turns it into a PHP Array. json_encode takes a PHP Array and turns it into a JSON string. so this part of your code doesn't make any sense to me.

$result = (var_dump(json_decode(json_encode($result),true)));

However, I realize now I mis-read an earlier post of yours. Do as @bobbybouwmann suggested and just paste the result of this....

$result = $mgClient->get("lists/$listAddress/members", array(
    'address' => $user->email
));

var_dump($result); exit;

This will tell us exactly what type of response you are getting so we know how to treat it when passing to your view and how to access the data inside of it.

Ticked's avatar

Running:

public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        var_dump($result); exit;

    }

Browser shows...

object(stdClass)[289]
  public 'http_response_body' => 
    object(stdClass)[290]
      public 'items' => 
        array (size=1)
          0 => 
            object(stdClass)[288]
              ...
      public 'total_count' => int 1
  public 'http_response_code' => int 200
Ticked's avatar

I found that this line works...

 $result = (var_dump(json_decode(json_encode($result),true)));

If I run:

    public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        json_decode($result);

    }

I get:

json_decode() expects parameter 1 to be string, object given

BENderIsGr8te's avatar

Ah. So your Mailgun response is an Object, not an array and not JSON. Essentially what you are doing with your json_decode(json_encode($object), true) is converting it to an associative array from an object.

If you want to access the result of the MailGun response in a view then you need to Map it out correctly. It appears this is an AJAX request because you are returning JSON instead of passing it to a view right? Either way, you just need to map the object correctly.

Let's take your original response, correctly indented and look at it.

{
    "http_response_body": {
    "items": [
        {
        "address": "test@testdomain.com",
        "name": "Patric Mongan",
        "subscribed": false,
        "vars": {}
        }
    ],
    "total_count": 1
    },
    "http_response_code": 200
}

Your Email address and name are in an array inside of a property.

$response->items->name (or $response->items['name']) should give you the name. Similar for email.

BENderIsGr8te's avatar

In other words, you can do this to get it to your view the way you want it....

$result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));
$info = $result->items;
return view ('status')->with($info);

Which would then let you in your view access

$info->name; // Or possibly $info['name']
$info->email; // Or possibly $info['email']
$info->subscribed; // Or possibly $info['subscribed']
Ticked's avatar

Thank you for your time... I'm sorry to be such a pain, but I really dot get this JSON thing... Accordingly with https://documentation.mailgun.com/api-email-validation.html#example it is JSON.

I have tried your kind suggestions:

public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        echo $result->items->name;

I get:

Undefined property: stdClass::$items

By changing the last line to:

echo $result->http_response_body->items->name;

I get:

Trying to get property of non-object

By changing the line to:

echo $result->http_response_body->items['name'];

I get:

Undefined index: name

Ticked's avatar

Lastly, implementing...

public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        $info = $result->http_response_body->items;
        return view ('account.subscriptions.newsletter.index')->with($info);

    }

On my view...

@extends('account.layouts.master')

@section('content')

    <div class="page-header">
        <h1>The Mayfair Magazine | <small>Account / Subscriptions</small></h1>
    </div>


    <div class="row">
        <div class="col-md-12 col-lg-8 col-lg-offset-2">

        <h3>Newsletter</h3>
        <hr>
        <p>Mailgun says:</p>

            {{ $info['name'] }}

        </div>
    </div>

@endsection

The browser shows:

ErrorException in 0145a2247fbfd2971a55a2e14146773f line 17: Undefined variable: info (View: /home/vagrant/www/themayfairmagazine/resources/views/account/subscriptions/newsletter/index.blade.php)

Ticked's avatar

I tried following a JQuery tutorial and I have things working... but Java is no really my cup of tea...

This works perfectly, just for reference...

@extends('account.layouts.master')

@section('content')

    <div class="page-header">
        <h1>The Mayfair Magazine | <small>Account / Subscriptions / Newsletter</small></h1>
    </div>


    <div class="row">
        <div class="col-md-12 col-lg-8 col-lg-offset-2">

            <h3>Newsletter</h3>
            <hr>
            <p>Hi <span class="data-name"></span> (<span class="data-address"></span>),</p>
            <p>Our newsletter mailing list members shows your status as:  <strong class="data-subscribed"></strong></p>

        </div>
    </div>



@endsection

@section('scripts')

    <script>

        var myRoute = '{{route('newsletterJson')}}';

        $.ajax({
            url:myRoute,
            dataType: 'json',
            type: 'get',
            cache: false,
            success: function(data){
                $(data.http_response_body.items).each(function(index, value){
                    $('.data-name').text(value.name);
                    $('.data-address').text(value.address);
                    $('.data-subscribed').text(value.subscribed);
                });
            }
        });
    </script>

@endsection
BENderIsGr8te's avatar

The "J" in JQuery is for JavaScript, which is a completely different and unrelated language than Java.

Your MailGun request is returning an Object. When you pass it to your response it is converted to JSON (which is JavaScript and JQuery's default datatype).

I apologize, when I "Re-indented" your code I still did not do it properly.

The "Name" is a property of "items". items is a property of "http_response_body". Finally, "data" is the name of the object containing your response in JQuery. So that is why it is working.

If you wanted to access these properties in PHP then it would have been this....

# Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        $info = $result->http_response_body->items;
        return view ('account.subscriptions.newsletter.index', compact('info'));

Should have allowed you to access them in your View as per below (remember with objects we use $item->property and in Array we use $item['property']. Since this is an object, in your view you should be able to access it like

<p>Mailgun says:</p>

            {{ $info->name }}

        </div>
Ticked's avatar

Thank you for the java - JavaScript explanation... I just become interested in coding very recently, I guess I have lots to learn.

Going back to PHP where I feel more comfortable... I tried:

    public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        $info = $result->http_response_body->items;

        echo $info->name;

    }

No luck... I get

ErrorException in SubscriptionsController.php line 51: Trying to get property of non-object

Anyway, thank you so much for your help and time.

Ticked's avatar
Ticked
OP
Best Answer
Level 1

I think I found the solution... honestly I don't know what is happening there so I cannot explain but you may understand and wish to share...

public function newsletterJsonPhp(){

        $user = User::first();

        # Mail gun - Instantiate the client.
        $mgClient = new Mailgun(env('MAILGUN_CLIENT'));
        $listAddress = env('MAILGUN_LIST_ADDRESS');

        # Mail gun - Issue the call to the client.
        $result = $mgClient->get("lists/$listAddress/members", array(
            'address' => $user->email
        ));

        foreach ($result->http_response_body->items as $obj) {
            echo $obj->address;
            echo $obj->name;
        }

Please or to participate in this conversation.