How do I run a foreach on a controller? - laravel

I want to send several emails, so that they are linked in a transition table, well all good, the problem is that when I use the command it only sends me an email and it is not repeated by each user as it should be because when using the foreach, I should send an email for each user that takes, at the same time review each query separately and if more than one user grabs me so I do not know why the command only sends me a single email. I hope you can help me and on the other hand I also want to use the email of the sis variable, but when using it within the 'mail' it tells me that said variable does not exist. Thanks for all beforehand.
my controller:
<?php
namespace App\Console\Commands;
use App\p;
use App\User;
use App\Pe;
use App\Mail\SendMailable;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
class Alertc extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'S:AC';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send works';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$hour= 14;
$minute= 0;
$second=0;
$year= date("Y");
$month= date("m");
$day=date("d");
$hourM=date("H");
$dayy= now();
$datelim=Carbon::Create($year,$month,$day,$hour,$minute,$second);
$datedif=Carbon::Create($year,$month,$day,$hourM,$minute,$second);
$dateen= $Datedif->addHour();
$intervalH= $dayy->diffInHours($datelim);
$intervalM= $dayy->diffInMinutes($dateen);
$systems = User::where('codarea','>',0)->get();
foreach ($systems as $system) {
$sis = User::select('users.email', 'users.id', 'users.name', 'p.description', 'p.Dateen')
->join('pa', 'pa.user', '=', 'users.id')
->join('p', 'p.coddate','=','pa.env')
->where('p.read_at', '=', 0, 'AND')
->where('pa.user', '=', $system->id)
->where('p.Dateen', '>', $dayy)
->get();
$data = ['name' => "Alert" , 'periods' => $sis, 'Periodres' => $intervalH, 'Periodresm' => $intervalM,
'Hactual' => $dayy, 'Hlimit' => $dateend];
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coopme#gmail.com', 'ALERT');
$message ->to('coopme#gmail.com')->subject('Alert');
});
return "La alert is finished";
}
}
}
my view:
<!DOCTYPE html>
<html>
<head>
<title>Message Sent</title>
</head>
<body>
<ul class="list-group">
Good morning the next works is:
#foreach($periods as $period)
<li class="list-group-item">
must send
<b>{{$period->description}}</b>
#if($Hactual<$Hlimit)
the limit is
{{$Periodres}} Hours and
{{$Periodresm}} Minutes.
#elseif($Hactual>$Hlimit)
is finished.
#endif
</li>
#endforeach
<b><h6>Always with you</h6></b>
</ul>
</body>
</html>
this is my controller when i want use the sis variable inside the mail:
namespace App\Console\Commands;
use App\p;
use App\User;
use App\Pe;
use App\Mail\SendMailable;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
class Alertc extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'S:AC';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send works';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$hour= 14;
$minute= 0;
$second=0;
$year= date("Y");
$month= date("m");
$day=date("d");
$hourM=date("H");
$dayy= now();
$datelim=Carbon::Create($year,$month,$day,$hour,$minute,$second);
$datedif=Carbon::Create($year,$month,$day,$hourM,$minute,$second);
$dateen= $Datedif->addHour();
$intervalH= $dayy->diffInHours($datelim);
$intervalM= $dayy->diffInMinutes($dateen);
$systems = User::where('codarea','>',0)->get();
foreach ($systems as $system) {
$sis = User::select('users.email', 'users.id', 'users.name', 'p.description', 'p.Dateen')
->join('pa', 'pa.user', '=', 'users.id')
->join('p', 'p.coddate','=','pa.env')
->where('p.read_at', '=', 0, 'AND')
->where('pa.user', '=', $system->id)
->where('p.Dateen', '>', $dayy)
->get();
$data = ['name' => "Alert" , 'periods' => $sis, 'Periodres' => $intervalH, 'Periodresm' => $intervalM,
'Hactual' => $dayy, 'Hlimit' => $dateend];
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coopme#gmail.com', 'ALERT');
$message ->to(sis->email)->subject('Alert');
});
return "La alert is finished";
}
}
}

Your query is:
$sis = User::select('users.email', 'users.id', 'users.name', 'p.description', 'p.Dateen')
->join('pa', 'pa.user', '=', 'users.id')
->join('p', 'p.coddate','=','pa.env')
->where('p.read_at', '=', 0, 'AND')
->where('pa.user', '=', $system->id)
->where('p.Dateen', '>', $dayy
->get();
It returns a collection. You need to foreach $sis and make an email array or use a method like first(), last()...
Something like this:
$message ->to($sis->first()->email)->subject('Alert'); //To send to the first user of your query

You're missing the $ character in this section:
$message ->to(sis->email)->subject('Alert');
Must be:
$message ->to($sis->email)->subject('Alert');

Related

Call to undefined method stdClass::isOnline() in Laravel 6

I'm trying to cheek the user is online or offline in my chat blade. I make a realtime chat in Laravel using Pusher and it's working fine but I have a issue to show user online offline status. I make middleware LastUserActivity and also registerd a my middleware in kernel.php but I constantly get this error.
Call to undefined method stdClass::save()
middleware
<?PHP
namespace App\Http\Middleware;
use Closure;
use Auth;
use Cache;
use Carbon\Carbon;
class LastUserActivity
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check()){
$expiresAt = Carbon::now()->addMinutes(1);
Cache::put('user-is-online-'.Auth::user()->id, true, $expiresAt);
}
return $next($request);
}
}
User Model
<?PHP
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Cache;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'gender', 'dob', 'image', 'password', 'is_admin', 'mobile', 'service_id', 'country_id', 'city_id', 'piincode'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
//check if User is online
public function isOnline()
{
return Cache::has('user-is-online-'. $this->id);
}
}
my blade file is
<ul class="users">
#foreach($users as $user)
<li class="user" id="{{ $user->id }}">
{{--will show unread count notification--}}
#if($user->unread)
<span class="pending">{{ $user->unread }}</span>
#endif
<div class="media">
<div class="media-left">
<img src="{{ URL::asset('storage/uploads/vendor/'.$user->image) }}" alt="" class="media-object">
</div>
<div class="media-body">
<p class="name">{{ $user->name }}</p>
<p class="email">{{ $user->email }}</p>
#if ($user->isOnline())
<li class="text-success">Online</li>
#else
<li class="text-muted">Offline</li>
#endif
</div>
</div>
</li>
#endforeach
</ul>
my controller file is
<?PHP
namespace App\Http\Controllers;
use App\Message;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Pusher\Pusher;
class ChatsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = DB::select("select users.id, users.name, users.image, users.email, count(is_read) as unread
from users LEFT JOIN messages ON users.id = messages.from and is_read = 0 and messages.to = " . Auth::id() . "
where users.id != " . Auth::id() . "
group by users.id, users.name, users.image, users.email");
return view('admin.chat', ['users' => $users]);
}
}
please help me. Thanks in advance
$users = DB::select("select users.id, users.name, users. ....
the $users will not hold a collection of user but a collection of std class ...
to hold a collection of users you should get the result using User Model ...
something like:
$users = User::selectRaw("users.id, users.name, users.image, users.email, count(is_read) as unread"
)->leftJoin('messages', 'users.id', 'messages.from')
->where('is_read', 0)->where('messages.to', Auth::id())
->where('users.id', '!=', Auth::id())
->groupBy(['users.id', 'users.name', 'users.image', 'users.email'])->get();

How to access variables from command in a view?

Good evening community.I'm executing a command on terminal, I want to access $per variable in my mail view and it is giving me an error that it can't recognize the $per variable.
This is the command code:
<?php
namespace App\Console\Commands;
use App\pamatrizinfoperio;
use App\Periodicidad;
use App\Mail\SendMailable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class EnvAlert extends Command
{
//public $periodos;
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'Send:Alert';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send Emails';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$pers = Periodicidad::select('paperiodicidad.des','pamatrizinfoperio.des', 'pamatrizinfoperio.codpar')
->join('pamatrizinfoperio', 'pamatrizinfoperio.cod_paperiodicidad', '=', 'paperiodicidad.cod')
->where('pamatrizinfoperio.read_at', '=', 0)
->get();
$data = array('name' => "Alert" , );
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coop#gmail.com', 'ALERT');
$message ->to('coop#gmail.com')->subject('Alert');
});
return "The alert was send";
}
}
And this is the view:
<!DOCTYPE html>
<html>
<head>
<title>Message Send</title>
</head>
<body>
<ul class="list-group">
#foreach($pers as $per)
<li class="list-group-item">
{{$per->des}}
{{$per->des}}
</li>
#endforeach
#endforeach
</ul>
</body>
</html>
I have the same variable in other views, with the same query in the code and it works normally only that I declare them in the controller, but in this case I do not know why it does not work for me, I hope you can help me, any data you need I will provide. Sorry if my English is a little bad, I would appreciate a lot to help me in this, because as you will notice the function of the system so to speak, it is only to send emails informing about a job and the time to deliver it. Thanks in advance for your time.
You are passing variable named $data to the mail and you are accessing a different variable in the mail view
In you case, Your handle function should be like this
public function handle(){
$pers = Periodicidad::select('paperiodicidad.des','pamatrizinfoperio.des', 'pamatrizinfoperio.codpar')
->join('pamatrizinfoperio', 'pamatrizinfoperio.cod_paperiodicidad', '=', 'paperiodicidad.cod')
->where('pamatrizinfoperio.read_at', '=', 0)
->get();
$data = ['name' => 'Alert',
'pers' => $pers];
Mail::send('emails.welcome', $data, function($message) {
$message ->from('coop#gmail.com', 'ALERT');
$message ->to('coop#gmail.com')->subject('Alert');
});
return "The alert was send";
}
Then you will be able to access the $pers in your mail view,
I hope it helped you :)

Get an attribute from one array in Mail blade Template

I cannot access to the attribute "price" in my Mail class in Laravel. I´ve got an error
Undefined index: price (View: C:\laragon\www\hr-english\resources\views\external__emails\registered-course.blade.php)
I think the problem is the controller. I had to do a query to the database to check the price of the course, because in my registered_courses table I have a foreign key related to courses which return to me the title of the course and its price.
When I got from the query those data and send the variables to the blade, it appears the error shown at the top.
My controller
public function store(Request $request)
{
try {
$data = $this->getData($request);
$email = Auth::user()->email;
$name = Auth::user();
$msg = $data;
$price = DB::table('courses')->select('price')->where('id', '=', $request['course_id'])->get();
RegisteredCourse::create($data);
Mail::to($email)->queue(new RegistCourse($msg, $email, $name, $price));
return redirect()->route('registeredCourse.index')
->with('sucess_message', 'Registered course was sucessfully added');
} catch(Exception $exception) {
return back()->withInput()
->withErrors(['unexpected_error' => 'Unexpected error occurred while trying to process your request.']);
}
}
My Mailable
class RegistCourse extends Mailable
{
use Queueable, SerializesModels;
public $subject = 'Registered Course';
public $msg;
public $email;
public $name;
public $price;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($msg, $email, $name, $price)
{
$this->msg = $msg;
$this->email = $email;
$this->name = $name;
$this->price = $price;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('external__emails.registered-course');
}
}
This is my blade template
<body>
<div class="container">
<div class="row">
<div>
<img src="{{asset('images/logo_leon.png')}}" alt="logo_leon" width="55" id="logo_login"><span style="color:gray">HOLYROOD ENGLISH SCHOOL</span>
</div>
<br>
<div>
<p>Thank you very much for your purchase, {{$name['name']}}. You have just registered in one of our courses.</p>
<p>
<table>
<tr>
<th>Name</th>
<th>Course</th>
<th>Date of purchase</th>
</tr>
<tr>
<td>{{$msg['course_id']}}</td>
<td>{{$price['price']}}</td>
</tr>
</table>
</p>
</p>
<p>See you in class. Surely we enjoy learning English.</p>
<p>If you have any questions, do not hesitate to contact us through any of our contact forms.</p>
<br>
<p>Equipo Holyrood English School</p>
</div>
</div>
</div>
</body>
</html>
In your code:
$data = $this->getData($request);
$email = Auth::user()->email;
$name = Auth::user(); // Should be Auth::user()->name (if name exists)
$msg = $data;
// The get() method returns an array even if there is one row.
$price = DB::table('courses')->select('price')->where('id', '=', $request['course_id'])->get();
So, $price should be $price[0]->price in the view or use first() method instead of get(). So, the name should be the property of the user model, Auth::user() will result in an object.
pay attention to the '->with' function that I use to send the datas to the view.
YOUR MAILING CLASS:
class SuccessBooking extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $booking;
public $user;
public $pdf_path;
public $rideCode;
public function __construct($user, $booking, $pdf_path, $rideCode)
{
$this->booking = $booking;
$this->user = $user;
$this->pdf_path = $pdf_path;
$this->rideCode = $rideCode;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('noreply#coride.com', "Co Ride Receipt")
->view('email/successbookinginvoice')
->attach(public_path($this->pdf_path))
->with([
'user' => $this->user,
'code' => $this->rideCode,
'path' => public_path($this->pdf_path),
'booking' => $this->booking,
]
);
}
}
YOUR BLADE TEMPLATE
#section('content')
{{--below we access a particular item in the object user--}}
<h5>Dear {{$user->firstName}}, congratulations on your successful booking.</h5>
{{--below we just access code, it's not an object--}}
<h5>Dear {{$code}}, congratulations on your successful booking.</h5>
#endsection

How to search in the multiple tables data in Laravel?

I'm new to Laravel, how get the multiples tables data for filter search purpose? I already view the data like id, topic name, standard name subject name but I searching topic it show topic name only but I need whatever I search its show the full data.
This is my tables name and what I need columns (three tables are different)
1. Topics -> id, topic_name
2. Standards -> standard_name
3. subject -> subject_name
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\TopicRequest;
use App\Topic;
use App\Standard;
use App\Subject;
use DB;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
class TopicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
**/
public function index()
{
$topics = Topic::leftJoin('standards','topics.standard_id', '=', 'standards.id')->
leftJoin('subjects','topics.subject_id', '=', 'subjects.id')
->select('topics.*' ,'standards.standard_name','subjects.subject_name')
->orderBy('id', 'ASC')
->paginate(10);
return view('topic.index', compact('topics'));
}
public function create()
{
$standards = Standard::select('id','standard_name')->paginate(10);
$subjects = Subject::select('id','subject_name')->paginate(10);
return view('topic.create', compact('standards','subjects'));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'standard_id' => 'required',
'subject_id' => 'required',
]);
$topic = new Topic([
'topic_name' => $request->get('name'),
'standard_id' => $request->get('standard_id'),
'subject_id' => $request->get('subject_id'),
]);
$topic->save();
return redirect()->route('topic.index')->with('success', 'Data Added');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$topic = Topic::find($id);
$standards = Standard::select('id','standard_name')->paginate(10);
$subjects = Subject::select('id','subject_name')->paginate(10);
return view('topic.edit', compact('topic', 'id','standards','subjects'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$topic = Topic::find($id);
$topic->topic_name = $request->get('name');
$topic->standard_id = $request->get('standard_id');
$topic->subject_id = $request->get('subject_id');
$topic->save();
return redirect()->route('topic.index')->with('success', 'Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$topic = Topic::find($id);
$topic->delete();
return redirect()->route('topic.index')->with('success', 'Data Deleted');
}
public function search()
{
$search = Input::get('search');
$topics = Topic::where( 'id', 'LIKE', '%' . $search . '%' )->orwhere( 'topic_name', 'LIKE', '%' . $search . '%' )->paginate(10);
return view('topic.index',compact('topics'));
}
}
If the search in the tables will be independent of each other; you must list the results separately by performing a separate search on each table.
If the tables to be searched depend on the search results in other tables, you cannot do this with eloquent orm. You must type raw sql.
If this is going to be a common procedure, I suggest you search for elastic search.

laravel notification does not work for me

I want to send an email to user with a message as below:
MessageController.php:
public function store(Request $request)
{
$user_id = auth()->user()->id;
$message = new Message;
$message->title = $request->title;
$message->body = $request->body;
$message->offer_id = $request->offer_id;
$message->user_id = $user_id;
$message->with_profile = $request->employeeProfile;
$message->save();
//return response()->json($message); -> this gives correct message
$offer = Offer::where('id', '=', $request->offer_id)->first();
//here I'm trying to get user Id, basing on offer (I knot I should use other way, but I'll correct it later
$user = User::where('id', '=', $offer->user_id)->first();
$user->notify(new OfferMessage($message)); -> this gives error "Undefined variable: message"
return response()->json(['created' => true], 201);
}
The problem is that it gives me an error: "Undefined variable: message", while I'm reciving correct message when I uncoment "return response()->json($message);"
What am I doing wrong here?
edit:
My Message.php class: (I don't have OfferMessage class)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use App\Notifications\OfferMessage;
class Message extends Model
{
use Notifiable;
}
edit2: Notifications/OfferMessage.php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\Message;
class OfferMessage extends Notification
{
use Queueable;
public $message;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('You've got new message: '.$message->offer_id)
->line($message->title)
->line($message->body)
->line('Sent by:'.$message->user_id)
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Change your OfferMessage Class toMail method
Change $message TO $this->message
public function toMail($notifiable)
{
return (new MailMessage)
->line("You've got new message: ".$this->message->offer_id)
->line($this->message->title)
->line($this->message->body)
->line('Sent by:'.$this->message->user_id)
->line('Thank you for using our application!');
}

Resources