Skip to content
Advertisement

How to send message to selected user with their name laravel

I’m trying to send a message to selected users with their names. So let’s say I have two users Ethan and Calvin then the message should start like User1:(Hi, Ethan), User2:(Hi, Calvin). So far the message is like (Hi, Ethan,Calvin) for every user. How can I fix this?

Blade

<form action="{{ route('mes.users') }}" method="POST">
    @foreach($users as $user)
    <textarea name="message"></textarea>
    <input type="checkbox" name="phone[]" @if(!old() || old('phone') == 'true') @endif value="
    {{ $user->phone }}">
    <input type="checkbox" name="name[]" value="{{ $user->name }}"/>
    <button type="submit" class="btn btn-primary">
        send Message
    </button>
    @endforeach
</form>

Controller

public function message(Request $request)
{
    $message = $request->input('message');
    $postData = $request->all();

    foreach ($postData['phone'] as $index => $value) {
        $postData['phone'][$index] = Str::replaceFirst('1', '965', $value);
    }
    foreach ($postData['name'] as $index => $names) {
        $postData['name'][$index] = $names;
    }
    $phone_number = implode(',', $postData['phone']);
    $name = implode(',', $postData['name']);


    $send_message = new MyHelper();
    $message = "Hi, $name $message";
    $send_message->sendMessage($phone_number, $message);
    return 'success';
}

Advertisement

Answer

It looks like it’s a problem with names and phones you also, sending message to $phone_number which looks like this 965XXXX,965XXXX,..., try this

$send_message = new MyHelper();

// assuming that $postData['name'] and $postData['phone'] have the same size

foreach ($postData['name'] as $index => $name) {

   $phone = Str::replaceFirst('1', '965', $postData['phone'][$index])
   $send_message->sendMessage($phone, "Hi, {$name} {$message}");

}

// this will send a message to the each phone number with corresponding user name
// (965XXXX,Ethan) and (965XXXX, Calvin)  

the full code will be

public function message(Request $request)
{
    $message = $request->input('message');
    $postData = $request->all();

    $send_message = new MyHelper();

    foreach ($postData['name'] as $index => $name) {

       $phone = Str::replaceFirst('1', '965', $postData['phone'][$index])
       $send_message->sendMessage($phone, "Hi, {$name} {$message}");

    }

    return 'success';
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement