Pass model to mail view - laravel

I have several methods that require email submissions. An example is, after making a purchase.
My class Mailable
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use App\Models\Order;
class AfterOrder extends Mailable
{
use Queueable, SerializesModels;
public $order;
public function __construct(Order $order)
{
$this->Order = $order;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->subject('Thanks for your purchase')->view('mail.after-order');
}
}
My mail view
<div class="container">
<h1>Nombre: {{\Auth::user()->email}}</h1>
<h1>Order: {{$order->reference}}</h1>
</div>
My Controller
public function sendMail(Order $order) {
$order = $order->newQuery();
$order->whereHas('user', function($query){
$query->where('email', '=', \Auth::user()->email);
});
$order = $order->orderBy('id', 'desc')->first();
$user = User::where('email', '=', \Auth::user()->email)->first();
Mail::to($user->email)->send(new AfterOrder($order));
//return redirect()->route('home')->with(['message' => 'Thank you for shopping at Sneakers!']);
}
What am I doing wrong? If I, for example, in my controller make a $ order-> reference I get the order reference but when passing the variable to the view it treats me as null or empty

You should use the with method
public function build()
{
return $this->view('mail.after-order')
->with([
'orderName' => $this->order->name,
'orderPrice' => $this->order->price,
]);
}
in your mailable class AfterOrder. With that you have access to the name and the price of the order in your mail view.
You can then access these with {{ $orderPrice }} and {{ $orderName }} in your view.

Was a typo. just change $this->Order = $order; to $this->order = $order;

Related

How to send email in laravel?

I want to send the data of the last order just made by the user
I already have my .env configured
AfterOrder Class: (Class type mail)
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use App\Models\Order;
class AfterOrder extends Mailable
{
use Queueable, SerializesModels;
public $order;
public function __construct(Order $order)
{
$this->Order = $order;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mail.after-order');
}
}
View:
<div class="container">
<h1>Name: {{$order->user->name}}</h1>
</div>
the user table is a belongsto of orders
Controller:
public function sendMail(Order $order) {
$order = $order->newQuery();
$order->whereHas('user', function($query){
$query->where('email', '=', \Auth::user()->email);
});
$order->orderBy('id', 'desc')->first();
$user = User::where('email', '=', \Auth::user()->email)->first();
Mail::to($user->email)->send(new AfterOrder($order));
//return redirect()->route('home')->with(['message' => 'Thank you for shopping at Sneakers!']);
}
Whats wrong? i got this error
$order is still a Builder object when you do this.
$order->orderBy('id', 'desc')->first();
To get the actual Model, you need to do the following:
$order = $order->orderBy('id', 'desc')->first();

Laravel generates error while sending lists of posts to users

RegistrationController.php
use App\User;
use App\Post;
use App\Notifications\LatestPosts;
use App\Notifications\WelcomeEmail:
public function store()
{
auth()->login($user);
$allUsers = User::latest()->get();
$posts = Post::latest()->get();
$user->notify(new WelcomeEmail($user));
$allUsers->notify(new LatestPosts($posts));
return redirect(‘/dashboard’);
}
WelcomeEmail.php
use App\User;
class WelcomeEmail extends Notification
{
use Queueable:
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function toMail($notifiable)
{
$user = $this->user;
return (new MailMessage)
->subject(‘Thanks for registering’)
->markdown(‘emails.newusers.welcome’, compact(‘user’));
}
}
LatestPosts.php
use App\Post;
class LatestPosts extends Notification
{
use Queueable;
public $posts;
public function __construct(Post $posts)
{
$this->posts = $posts;
}
public function toMail($notifiable)
{
$posts = $this->posts;
return (new MailMessage)
->subject(‘Latest posts for you’)
->markdown(‘emails.posts.latestposts’, compact(‘posts’));
}
}
New users register successfully, welcome email is sent successfully but it gives me this error for sending latest posts to users.
Argument 1 passed to App\Notifications\LatestPosts::__construct() must be an instance of App\Post, instance of Illuminate\Database\Eloquent\Collection given
Basically, I want to send a list of posts to all users (I know it’s not efficient to send it while new users register but just want to see how it will work out even if I send it while new users register) Someone please help me out in this. What do I do? Thanks in advance.
In registration controller
use App\User;
use App\Post;
use App\Notifications\LatestPosts;
use App\Notifications\WelcomeEmail:
public function store()
{
auth()->login($user);
$allUsers = User::latest()->get();
$posts = Post::latest()->get();
$user->notify(new WelcomeEmail($user));
foreach($allUsers as $u){
$u->notify(new LatestPosts($posts));
}
return redirect(‘/dashboard’);
}
LatestPost
use App\Post;
use Illuminate\Database\Eloquent\Collection;
class LatestPosts extends Notification
{
use Queueable;
public $posts;
public function __construct(Collection $posts)
{
$this->posts = $posts;
}
public function toMail($notifiable)
{
$posts = $this->posts;
return (new MailMessage)
->subject(‘Latest posts for you’)
->markdown(‘emails.posts.latestposts’, compact(‘posts’));
}
}
You should change the signature of your constructor:
use App\Post;
use Illuminate\Database\Eloquent\Collection;
class LatestPosts extends Notification
{
use Queueable;
public $posts;
public function __construct(Collection $posts) // use `Collection`, not `Post`
{
$this->posts = $posts;
}
public function toMail($notifiable)
{
$posts = $this->posts;
return (new MailMessage)
->subject('Latest posts for you')
->markdown('emails.posts.latestposts', compact('posts'));
}
}

laravel:send notification with (data) when update a record

Problem: how can I display data with update function?
the notification is sent but witout data that I specified in this function :
public function toDatabase($notifiable)
{
return [
'data'=>$this->booking->num_ch
];
}
it works with store function but it dosn't with update function
my notification class:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use App\Booking;
class NewMessage extends Notification
{
use Queueable;
public $booking;
public function __construct(Booking $booking)
{
//
$this->booking = $booking;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'data'=>$this->booking->num_ch
];
}
my update function :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Booking;
use App\User;
use Notification;
use App\Notifications\NewMessage;
class DispoController extends Controller
{
public function update(Request $request,$id,Booking $booking)
{
//
Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
it shows just "new booking"
#foreach(Auth::user()->unreadNotifications as $not)
<li>
<a class="dropdown-item" >new booking {{$not->data['data']}}</a>
</li>
#endforeach
public function update(Request $request,$id,Booking $booking)
{
//
Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage(Booking::findOrFail($id)));
// notification
return redirect()->route('info_client.index')->with(['success'=>'succés']);
}
The issue is your not capturing the saved booking, should be like so
public function update(Request $request,$id,Booking $booking)
{
//
$booking = Booking::findOrFail($id)->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
So your passing in an empty booking from the function call and passing that to the notification and not the updated record.
But you can simplify the whole thing by doing this
public function update(Request $request, Booking $booking)
{
//
$booking->update([
'num_ch'=>$request->num_ch,
'type'=>$request->type,
'statut'=>$request->statut,
'enfants'=>$request->enfants,
'adultes'=>$request->adultes,
]);
auth()->user()->notify(new NewMessage($booking)); // notification
return redirect()->route('booking.index')->with(['success'=>'succés']);
}
So instead of passing both id and booking just pass in the booking which should automatically be found from the Route and container.

Unable to show data in Laravel

I am adding a feature in chatter package and now am unable to show data on my view
this is the code of controller ChatterreplyController.php
<?php
namespace DevDojo\Chatter\Controllers;
use Illuminate\Http\Request;
use DevDojo\Chatter\Models\Chatterreply;
use Auth;
use Carbon\Carbon;
use DevDojo\Chatter\Events\ChatterAfterNewDiscussion;
use DevDojo\Chatter\Events\ChatterBeforeNewDiscussion;
use DevDojo\Chatter\Models\Models;
use Illuminate\Routing\Controller as Controller;
use Event;
use Validator;
class ChatterreplyController extends Controller
{
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
return back()->with('chatter_alert','Add Comment Successfully');
}
public function show(Chatterreply $chatterreply ,$id)
{
$chatterreplies = Chatterreply::where('chatter_post_id',$id)->get();
return view('chatter::discussion', compact('chatterreplies'));
echo "<pre>"; print_r('$chatterreplies'); die;
}
}
this is the view page discussion.blade.php
#foreach($chatterreplies as $chatterreply)
{{$chatterreply->reply}}
#endforeach
try this:
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
return redirect('/discussion')->with('chatter_alert','Add Comment Successfully');
}

I can't update the field in laravel 5

It is OK in Get, Post, Delete in my laravel code.
But I can't update the field.
function update in BookController.php
$data = $this->request->all();
If show the dd($data), it is null.
What reason?
Help me please.
BookRequest.php Code:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BookRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|max:255',
'coment' => 'required'
];
}
}
BookController.php Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
protected $request;
protected $book;
public function __construct(Request $request, Book $book) {
$this->request = $request;
$this->book = $book;
}
public function update(BookRequest $request, $id) {
$data = $this->request->all();
$book = $this->book->find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
return response()->json(['status' => Response::HTTP_OK]);
}
}
If i were you i would replace the Controller like below:
<?php
namespace App\Http\Controllers;
use App\Book;
use Illuminate\Http\Response;
use App\Http\Requests\BookRequest;
class BookController extends Controller
{
public function update(BookRequest $request, $id) {
$book = Book::find($id);
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}
}
If you have set up Route:model binding then you can simplify Code more better. Below code only works if you have a Route::model setup in your route file web.php.
Check this docs for more details:
https://laravel.com/docs/5.6/routing#route-model-binding
public function update(BookRequest $request, Book $book) {
$book->update($request->all());
return response()->json(['status' => Response::HTTP_OK]);
}
Try this:-
$request->all();
instead of
$this->request->all()
I have solved.
My request: http://127.0.0.1:8000/api/book
POST , key: _method: PUT
Update Code
$data = $request->all();
$book = Boook::find($id);
$book->name = $data['name'];
$book->coment = $data['coment'];
$book->save();
Regards.

Resources