laravel 8 markdown email image not showing - laravel

I'm dispatching a markdown email using the Laravel's mailable class.
Here's the following code for the mailable.
<?php
namespace App\Mail;
use App\traits\Mail\RecordMailTrait;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Laravel\Spark\Invitation;
class ExistingUserCompanyInviteMail extends Mailable
{
use Queueable, SerializesModels, RecordMailTrait;
/**
* Create a new message instance.
*
* #return void
*/
protected $invite;
public $inviter;
public $view = 'email.invitation-to-current-user';
public function __construct(Invitation $invite, User $inviter)
{
$this->invite = $invite;
$this->inviter = $inviter;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$invitation = $this->invite;
$view = $this->view;
$to = $this->to[0]['address'];
$sent_by_email = $this->inviter->email;
$this->withSwiftMessage(function ($message) use($invitation, $view, $to, $sent_by_email){
$message->view = $view;
$message->sent_to_email = $to;
$message->sent_by_email = $sent_by_email;
$message->mailable_type = Invitation::class;
$message->mailable_id = $invitation->id;
});
return $this->markdown($this->view,['invitation' => $this->invite, 'inviter' => $this->inviter, 'entity' => $this->invite->team->name, 'url' => url('/home/invitations')])->subject("Invitation");
}
}
I get the email in my inbox, with the correct text and styling, however not the image, it doesn't load as it should.
Here's the code for the HTML:
<tr>
<td class="header">
<a href="{{ $url }}" style="display: inline-block;">
<img src="{{ asset('/img/logo.svg')}}" class="logo" alt="logo1">
</a>
</td>
</tr>
This is the URL I get from the image in the sent email:
https://ci3.googleusercontent.com/proxy/8oh80_LJVyfK50ZObX23alnA8vhDzf3vXWJC_kHVgccnfzs-zSher-TbH9fO4RcDWjTQ5s8c_q3V6qc=s0-d-e1-ft#http://core-hosp.test/img/logo.svg
logo does not show (image of email)

Related

Cron Job doesn't work on CPanle using Laravel Project

I'm trying to run a schedule task on cpanel.
So I'm using the following code :
Command : notify.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Mail\NotifyContratExpire;
use Mail;
use Carbon\Carbon;
use App\Models\Projet_Casting;
use App\Models\Filiale;
class notify extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'emails:send';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Send Emails notify to all users for contrats expirés';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
$today_date = Carbon::now()->addDays(60);
$contrat_email = Projet_Casting::join('contrats','contrats.id_contrat','=','projets_castings.id_contrat')->leftjoin('projets','projets.id_projet','=','projets_castings.id_projet')->join('castings','castings.id_casting','=','contrats.id_casting')->join('filiales','projets.id_filiale','=','filiales.id_filiale')->where('contrats.actif',1)->where('contrats.date_fin_contrat', '<=', $today_date)->distinct('filiales.id_filiale')->get();
$emails = array();
foreach($contrat_email as $key) {
$emails[] = json_decode($key->adm_email);
}
$email_send = array();
foreach ($emails as $key3 => $value) {
$filiale =Filiale::where('adm_email', json_encode($value))->select('filiales.id_filiale')->value('filiales.id_filiale');
$contras = Projet_Casting::join('contrats','contrats.id_contrat','=','projets_castings.id_contrat')->leftjoin('projets','projets.id_projet','=','projets_castings.id_projet')->join('castings','castings.id_casting','=','contrats.id_casting')->where('contrats.actif',1)->where('contrats.date_fin_contrat', '<=', $today_date)->where('projets.id_filiale',$filiale)->get();
foreach($value as $val =>$v){
Mail::to($v)->send(new NotifyContratExpire($contras));
}
}
}
}
MailController : NotifyContratExpire
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class NotifyContratExpire extends Mailable
{
use Queueable, SerializesModels;
public $contras;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($contras)
{
$this->contras = $contras;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->subject("contrats")->view('Template_Mails.template_email')->with('contras',$this->contras);
}
}
And kernel.php :
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Mail;
use Illuminate\Console\Command;
use App\Mail\NotifyContratExpire;
use Carbon\Carbon;
use App\Models\Projet_Casting;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
/*'\App\Console\Commands\notify'*/
Commands\notify::class,
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
$schedule->command('emails:send')->everyMinute()->withoutOverlapping(60);
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
And the email view :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<table class="data-table data-table-standard responsive nowrap"
data-order="[[ 1, "desc" ]]">
<thead>
<tr>
<th>numero_contrat</th>
<th>numero_projet</th>
<th>casting</th>
<th>casting</th>
</tr>
</thead>
<tbody>
#foreach($contras as $contra)
<tr>
<td>
<p class="list-item-heading">{{$contra->numero_contrat}}</p>
</td>
<td>
<p class="text-muted">{{$contra ->numero_projet}}</p>
</td>
<td>
<p class="text-muted">{{$contra->nom}}</p>
</td>
<td>
<p class="text-muted">{{$contra->prenom}}</p>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</body>
</html>
On cpanel I have the following structure :
And I created a cron JOV for everyMinute with the following command :
/usr/local/bin/php /home/current_user/laravel/artisan schedule:run
the mails are not sent and I do not know where the error is or how to display the errors to know how to solve this problem, when I run the execution in localhost, it works very well and the emails are sent.
If you have any idea , please help
You can try this
/path/to/php /path-to-your-project/artisan schedule:run >>/dev/null 2>&1

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();

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

Laravel - Pass custom data to email view

Following on from a previous question, I have an email controller set up to correctly pass user data to the view. I am now trying to modify it so I can pass some custom data instead. My controller looks like this...
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $email_data;
public function __construct($email_data)
{
$this->email_data = $email_data;
}
public function build()
{
return $this->view('emails.welcome')->with(['email_data' => $this->email_data]);
}
}
And I am sending the email like this...
/* Create Data Array For Email */
$email_data = array(
'first_name'=>'John',
'last_name'=>'Doe',
'email'=>'john#doe.com',
'password'=>'temp',
);
/* Send Email */
Mail::to($user->email)->send(new Welcome($email_data));
Is this correct? When I try using this method it does not seem to be passing the data through to the email template. How can I then access this data within the view?
Have you tried this way ?
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct($data)
{
$this->data = $data;
}
public function build()
{
return $this->view('emails.welcome')->with('data', $this->data);
}
}
and then in your controller from where you are creating your array of data,
$data = [
'first_name'=>'John',
'last_name'=>'Doe',
'email'=>'john#doe.com',
'password'=>'temp'
];
\Mail::to($user->email)->send(new Welcome($data));
Please make sure that you add
use Mail;
use App\Mail\Welcome;
in your controller.
You can access the data in your view like this
{{ $data['first_name'] }}
{{ $data['last_name'] }}
{{ $data['email'] }}
{{ $data['password'] }}
OR
You can also try Markdown mails for this
You don't need this part ->with(['email_data' => $this->email_data]) because if the property is public you can access it in the view.
And you are passing an array so you have to access the values like this :
$email_data['email'] // ...
There are two ways to pass data through the view. First, any public defenses defined in the mailable class pass automatically through the view.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $firstName;
public $lastName;
public $email;
public $password;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($firstName, $lastName, $email, $password)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->email = $email;
$this->password = $password;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders');
}
}
In Blade view
<div>
First Name: {{ $firstName }}
Last Name: {{ $lastName }}
Email: {{ $email }}
Password: {{ $password }}
</div>
For variables with protected and private properties, it is possible to pass data through a view with the with method
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
protected $firstName;
protected $lastName;
protected $email;
protected $password;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($firstName, $lastName, $email, $password)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
$this->email = $email;
$this->password = $password;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('emails.orders')->with([
'first_name'=> $this->firstName,
......
]);
}
}
In Blade view
<div>
First Name: {{ $firstName }}
Last Name: {{ $lastName }}
Email: {{ $email }}
Password: {{ $password }}
</div>

Laravel 5: Cannot access Eloquent relationship data

After trying out every solution I found on Google, I still cannot seem to access my relationship's data. I keep getting the following error:
Trying to get property of non-object (View: /home/eneko/foundry/biome/resources/views/home.blade.php)
Here are the files that load for this route:
Fruitu.php
<?php namespace Biome;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\SluggableInterface;
use Cviebrock\EloquentSluggable\SluggableTrait;
class Fruitu extends Model implements SluggableInterface {
use SluggableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'fruitus';
public function toString() {
return $this->izenburua;
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['izenburua', 'irudia', 'edukia'];
public function egilea() {
return $this->belongsTo('Biome\User');
}
protected $sluggable = array(
'build_from' => 'izenburua',
'save_to' => 'slug',
);
}
The controller function:
public function index()
{
$fruituak = Fruitu::all();
$fruituak->load('egilea');
return view('home')->with(compact('fruituak'));
}
The loop in the blade template:
#foreach ($fruituak as $fruitu)
<div class="fruitua">
<a href="{{ route('fruitu.show', $fruitu->slug) }}">
<h3>{{ $fruitu->izenburua }}</h3>
</a>
{{ $fruitu->egilea->name }}
<p class="eduk">{{ $fruitu->edukia }}</p>
</div>
#endforeach
Thanks in advance for your help!

Resources