How to pass data from database to Mailable? - laravel

I know how to pass data to view but how do you pass data to a mailable? I'm also a bit confused on where to put the database call DB::select, in the controller or the mailable? So far I've tried this:
web.php:
Route::get('/test-email', 'App\Http\Controllers\TestMailController#test');
TestMailController.php:
<?php
namespace App\Http\Controllers;
use App\Mail\ContactMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class TestMailController extends Controller
{
public function test()
{
return new ContactMail();
}
}
TestMail.php:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
class TestMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $data;
public function __construct()
{
$this->data = DB::select('select * from db_name');
}
public function build()
{
return $this->markdown('emails.testmail')->with('data', $data);
}
}

You need to use $this :
public function build()
{
return $this->markdown('emails.testmail')->with('data', $this->data);
}

Related

How to pass user data into a JSON file using Laravel one to one

I am having issues getting user data in a JSON file am using one to one relationship
this is my PostRequest Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PostRequest extends Model
{
use HasFactory;
public function user(){
return $this->belongsTo(User::class, 'artisan_id');
}
}
User model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laratrust\Traits\LaratrustUserTrait;
use App\Models\Verify;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use LaratrustUserTrait;
use HasFactory, Notifiable;
public function PostRequest(){
return $this->hasOne(PostRequest::class, 'artisan_id');
}
}
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\PostRequest;
use App\Models\User;
class ChatController extends Controller
{
public function getMessages(){
return view('user/message'); //response()->json($contacts);
}
public function getContact(){
$email = Auth::user()->email;
$contacts = PostRequest::select('artisan_id')->where('email', '=', $email)
->limit('1')
->orderBy('id', 'DESC')
->user();
return response()->json($contacts);
//}
}
}
if run the above controller I get this error msg
[14:09:51] LOG.error: Call to undefined method Illuminate\Database\Eloquent\Builder:: user() {"userId":15,"exception":{}
If I run this I get all data, buh den I need a specific data
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\PostRequest;
use App\Models\User;
class ChatController extends Controller
{
public function getMessages(){
return view('user/message'); //response()->json($contacts);
}
public function getContact(){
$email = Auth::user()->email;
$contacts = PostRequest::all();
return response()->json($contacts);
//}
}
}
Just try this query:
$email = Auth::user()->email;
$contacts = PostRequest::where('email', $email)->first()->user;
return response()->json($contacts);

Laravel 6 Event Listener Mailable Queue unable to access

Environment:
php: 7.4.2
laravel: 6.15.0
Scenario: Upon user registration, event(new NewUserHasRegisteredEvent($user)); is triggered.
In my EventServiceProvider.php
protected $listen = [
NewUserHasRegisteredEvent::class => [
\App\Listeners\WelcomeNewUserListener::class,
],
];
My NewUserHasRegisteredEvent.php
<?php
namespace App\Events;
use App\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewUserHasRegisteredEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
}
My WelcomeNewUserListener.php Note that it implements ShouldQueue
<?php
namespace App\Listeners;
use App\Events\NewUserHasRegisteredEvent;
use App\Mail\WelcomeUserMail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Mail;
class WelcomeNewUserListener implements ShouldQueue
{
public function __construct()
{
//
}
public function handle(NewUserHasRegisteredEvent $event)
{
Mail::to($event->user->email)->send(new WelcomeUserMail($event->user));
}
}
My WelcomeUserMail.php
<?php
namespace App\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class WelcomeUserMail extends Mailable
{
use Queueable, SerializesModels;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function build()
{
return $this->markdown('emails/new-welcome')
->with('user', $this->user);
}
}
My new-welcome.blade.php
#component('mail::message')
Hello {{ $user->name ?? 'name' }}, ...
#endcomponent
Issue: When the user receives the registration email, the $user->name is not defined hence i'm using ?? operator. Weird thing is when I remove the ShouldQueue from the WelcomeNewUserListener.php then the $user->name works perfectly fine.
Please suggest. I want to use queue via event/listeners way.

Target [App\Repositories\Setting\SettingRepositoryContract] is not instantiable while building [App\Http\Controllers\SettingsController]

How can i solve Target [App\Repositories\Setting\SettingRepositoryContract] is not instantiable while building [App\Http\Controllers\SettingsController].
Here is my controller
namespace App\Http\Controllers;
use Auth;
use Session;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Repositories\Setting\SettingRepositoryContract;
class SettingsController extends Controller
{
protected $settings;
public function __construct(
SettingRepositoryContract $settings
)
{
$this->settings = $settings;
}
SettingRepositoryContract
namespace App\Repositories\Setting;
interface SettingRepositoryContract
{
public function getCompanyName();
public function updateOverall($requestData);
public function getSetting();
}
NOTE: I am new to laravel and can't understand this error. So please help me if anyone know the answer.
Thank you
You need to do it right way:
SettingsRepositoryInterface
namespace App\Repositories;
interface SettingsRepositoryInterface
{
public function getCompanyName();
public function updateOverall($requestData);
public function getSetting();
}
Implement the interface SettingsRepository
namespace App\Repositories;
use App\Repositories\SettingsRepositoryInterface;
class SettingsRepository implements SettingsRepositoryInterface
{
public function getCompanyName()
{
// your code here
}
// all other functions here
}
Create a new service provider SettingsRepositoryServiceProvider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class SettingsRepositoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(
'App\Repositories\SettingsRepositoryInterface',
'App\Repositories\SettingsRepository');
}
}
Register your service provider by adding it to config/app.php
App\Providers\SettingsRepositoryServiceProvider::class,
And finally in your controller
namespace App\Http\Controllers;
use Auth;
use Session;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Repositories\SettingsRepositoryInterface;
class SettingsController extends Controller
{
protected $settings;
public function __construct(SettingsRepositoryInterface $settings)
{
$this->settings = $settings;
}
}
For your reference:
https://laravel.com/docs/6.x/container &
https://laravel.com/docs/6.x/providers
Modify namespace according to your needs.

Laravel repository Class App\Repository\User does not exist

Hello I want to use my own repository class in my Laravel 5.8 project
I created my file Repository in the App File and in this file I added A class called ConversationRepository
This is my class:
<?php
namespace App\Repository;
class ConversationRepository{
private $user;
public function __construct(User $user){
$this->user=$user;
}
public function getConversation(int $userId){
return $this->user->newQuery()
->select('name','id')
->where('id','!=',$userId)
->get();
}
}
And then when I use it on my controller :
<?php
namespace App\Http\Controllers;
use App\User;
use Auth;
use Illuminate\Http\Request;
use App\Repository\ConversationRepository;
class ConversationsController extends Controller
{
private $r;
private $auth;
public function __construct(ConversationRepository $conversationRepository,AuthManager $auth){
$this->r = $conversationRepository;
$this->auth = $auth;
}
public function index(){
return view('conversation.index',[
'users'=>$this->r->getConversation($this->auth->user()->id)
]);
}
public function show(User $user){
return view('conversation.show',['users'=>$this->r->getConversation(
$this->auth->user()->id),
'user'=>$user
]);
}
public function store(User $user){
}
}
I get the error
Class App\Repository\User does not exist
Apparently, you forgot to add use App\User; in the class ConversationsController file.

I get the Object not found error while trying to output all users details from database

I am trying to out all users on my admin dashboard by parsing the result through to my route
Here is my controller;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\User;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('notAdmin');
}
public function index(){
$user = User::all()->orderBy('id', 'desc')->paginate(100);
return view('admin-dashboard')->with('users', $users);
}
}
I get the "Method Illuminate\Database\Eloquent\Collection::orderBy does not exist." error
You have applied wrong query:
You don't need to add all() as you are using paginate
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\User;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth');
$this->middleware('notAdmin');
}
public function index(){
$users = User::orderBy('id', 'desc')->paginate(100);
return view('admin-dashboard')->with('users', $users);
}
}

Resources