I have to define List ID and MailChimp API Key in my .env file. I'm sure both are fine even I am not getting any error but email in not inserting in my List I installed https://github.com/spatie/laravel-newsletter (spatie/laravel-newsletter) Package.
Here is my method
public function subscribe(Request $request)
{
$email = request('email');
Newsletter::subscribe($email);
Session::flash('subscribed', 'Successfully subscribed.');
return redirect()->back();
}
Then I check subscribe Method in Newsletter.php
it is as
public function subscribe($email, $mergeFields = [], $listName = '', $options = [])
{
$list = $this->lists->findByName($listName);
$options = $this->getSubscriptionOptions($email, $mergeFields, $options);
$response = $this->mailChimp->post("lists/{$list->getId()}/members", $options);
if (! $this->lastActionSucceeded()) {
return false;
}
return $response;
}
I print options variable it returns output as
array:3 [▼
"email_address" => "bluemoon#gmail.com"
"status" => "subscribed"
"email_type" => "html"
]
Then I print below variable $response it returns false Please Help whats wrong with this.
Thanks In advance
Not sure this will directly resolve your issue, but you need to run the following command in your terminal:
php artisan vendor:publish --provider="Spatie\Newsletter\NewsletterServiceProvider"
This creates a laravel-newsletter.php in the config directory, that's where your List ID and MailChimp API key should go.
PS: the package seems to have an issue with env so don't use it, just enter your keys as strings.
Related
I have a form that using ajax for update data client. In that form there is an input file. Everything is going fine except for updating the file. File is sent, it changed on storage too, but it gives error on validation and didn't change data on database.
Here is the code on the controller :
public function update(Request $request, Client $client)
{
$validatedData = Validator::make($request->all(), [
'name' => 'required|max:255',
'logo'=> 'image|file|max:100',
'level' => 'required|max:1'
]);
$validatedData['user_id'] = auth()->user()->id;
if ($validatedData->fails()){
return response()->json($validatedData->errors());
} else {
if($request->file('logo')){
if($request->oldLogo){
Storage::delete($request->oldLogo);
}
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
}
$validateFix = $validatedData->validate();
Client::where('id', $client->id)->update($validateFix);
return response()->json([
'success' => 'Success!'
]);
}
}
It gives error on line :
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
With message :
"Cannot use object of type Illuminate\Validation\Validator as array"
I use the same code that works on another case, the difference is the other not using ajax or I didn't use Validator::make on file input. I guess it's just wrong syntax but I don't really know where and what it is.
To retrieve the validated input of a Validator, use the validated() function like so:
$validated = $validator->validated();
Docs:
https://laravel.com/docs/9.x/validation#manually-creating-validators
https://laravel.com/api/9.x/Illuminate/Contracts/Validation/Validator.html
$validatedData is an object of type Illuminate\Validation\Validator.
I would say the error is earlier there as well as this line should give an error also:
$validatedData['user_id'] = auth()->user()->id;
As ericmp said, you first need to retrieve the validateddata to an array and then work with it.
I am trying to edit but unfortunately i am facing error please help me how to fix that thanks.
please check error
https://flareapp.io/share/dmk2jl53
Argument 1 passed to App\Http\Controllers\CMS\ProjectCredentialCpanelController::edit() must be an instance of App\ProjectCredentialCpanel, string given
controller
public function edit(ProjectCredentialCpanel $projectcredentialcpanel,$projectId)
{
$data = [
'project' => $projectId,
'isEdit' => true,
];
return view('cms.credential.cpanel.add-cpanel', $data);
}
route
Route::get('project/credential/{projectId}/cpanel/{projectcredentialcpanel}/edit', 'ProjectCredentialCpanelController#edit')->name('project.cpanel.edit');
for route model binding the name of model you want to bind(variable) should match URI segment.
https://laravel.com/docs/7.x/routing#implicit-binding .
so it will be:
public function edit($projectId, ProjectCredentialCpanel $projectcredentialcpanel)
{
$data = [
'project' => $projectId,
'isEdit' => true,
];
return view('cms.credential.cpanel.add-cpanel', $data);
}
What do I have:
Lumen service which processing particular Job
Laravel portal which sending file to that service for processing by it
Once it was using only JS and Ajax it worked almost fine - the only what I had to implement is CORS middleware. However after I moved logic to JWT (using jwt-auth package) and GuzzleHttp (I'm using it to send requests to service API) Job stopped processing throught database queue instead it running as if Queue driver being set to sync.
Following is controller which I'm calling during API call:
public function processPackageById(Request $request) {
$id = $request->package_id;
$package = FilePackage::where('id', '=', $id)->where('package_status_id', '=', 1)->first();
if($package) {
Queue::push(new PackageProcessingJob(
$this->firm,
$this->accounts,
$package
));
return 'dispatching done for ' . $id;
}
return 'dispatching not done for ' . $id;
}
where $this->firm and $this->accounts are injected Repositories for particular models. FilePackage object being created on Laravel site and both shares same database to work with.
As result no job being incerted into jobs table. When I use Postman everything is fine. However when I'm trying to send request from Laravel backend:
public function uploaderPost(Request $request)
{
// Here we get auth token and put into protected valiable `$this->token`
$this->authorizeApi();
$requestData = $request->except('_token');
$package = $requestData['file'];
$uploadPackageRequest =
$this->client->request('POST', config('bulk_api.url') .'/api/bulk/upload?token=' . $this->token,
[
'multipart' => [
[
'name' => 'file',
'contents' => fopen($package->getPathName(), 'r'),
'filename' => $package->getClientOriginalName(),
],
]
]);
$uploadPackageRequestJson = json_decode($uploadPackageRequest->getBody()->getContents());
$uploadPackageRequestStatus = $uploadPackageRequestJson->status;
if($uploadPackageRequestStatus == 1) {
$package = BulkUploadPackage::where('id', '=',$uploadPackageRequestJson->id)->first();
// If package is okay - running it
if($package !== null){
// Here where I expect job to be dispatched (code above)
$runPackageRequest =
$this->client->request('POST', config('api.url') .'/api/bulk/run?token=' . $this->token,
[
'multipart' => [
[
'name' => 'package_id',
'contents' => $package->id
],
]
]);
// Here I'm receiving stream for some reason
dd($runPackageRequest->getBody());
if($runPackageRequest->getStatusCode()==200){
return redirect(url('/success'));
}
}
}
return back();
}
Could anyone advise me what is wrong here and what causes the issue?
Thank you!
Alright, it was really interesting. After echoing config('queue.default') in my contoller it appeared that it's value indeed sync nevertheless that I set everything correctly.
Then I assumed that maybe the reason in Laravel itself and its variables. Indeed in .env file from Laravel side QUEUE_DRIVER being set to sync. After I changed it to QUEUE_DRIVER=database everything started working as expected.
Hope that will help someone in future.
In laravel 5.2 this worked just fine, but since migrating to 5.3 i'm having issues getting the category sent in my email.
public function build()
{
return $this->view('mail.enquiry')
->getSwiftMessage()->getHeaders()->addTextHeader('X-SMTPAPI', json_encode(array("category" => array(env('BUSINESS_NAME')))))
->subject('Website Enquiry')
->to(env('MAIL_DEFAULT_TO_EMAIL'), env('MAIL_DEFAULT_TO_NAME'))
->from(env('MAIL_DEFAULT_FROM_EMAIL'), env('MAIL_DEFAULT_FROM_NAME'))
->replyTo(\Request::get('email'), \Request::get('full_name'));
}
i get this error
BadMethodCallException in Mailable.php line 525:
Method [getSwiftMessage] does not exist on mailable.
every thing in this code works fine, but breaks as soon as I add this line:
->getSwiftMessage()->getHeaders()->addTextHeader('X-SMTPAPI', json_encode(array("category" => array(env('BUSINESS_NAME')))))
To achieve what you're after you can use the withSwiftMessage() method.
This method takes a callback which will be passed the instance of SwiftMessage:
->withSwiftMessage(function ($message) {
$message->getHeaders()->addTextHeader('X-SMTPAPI', json_encode(array("category" => array(env('BUSINESS_NAME')))));
})
So your method would look something like:
public function build()
{
return $this->view('mail.enquiry')
->withSwiftMessage(function ($message) {
$message->getHeaders()->addTextHeader('X-SMTPAPI', json_encode(array("category" => array(env('BUSINESS_NAME')))));
})
->subject('Website Enquiry')
->to(env('MAIL_DEFAULT_TO_EMAIL'), env('MAIL_DEFAULT_TO_NAME'))
->from(env('MAIL_DEFAULT_FROM_EMAIL'), env('MAIL_DEFAULT_FROM_NAME'))
->replyTo(\Request::get('email'), \Request::get('full_name'));
}
Hope this helps!
Since I visited this question when looking for a solution on Laravel 8 I'm adding some more info to the already accepted answer:
In Laravel 8 now you can follow instructions here: https://sendgrid.com/docs/for-developers/sending-email/laravel/ and check section titled "Adding a category or custom field".
It does still use withSwifthMessage() - more info for this on laravel's site: https://laravel.com/docs/8.x/mail#customizing-the-swiftmailer-message
The gist of it is simillar to the already accepted answer, but provides some nice helpers too and clearer code:
In your build() function:
$headerData = [
'category' => 'category',
'unique_args' => [
'variable_1' => 'abc'
]
];
$header = $this->asString($headerData);
$this->withSwiftMessage(function ($message) use ($header) {
$message->getHeaders()
->addTextHeader('X-SMTPAPI', $header);
});
return $this->view('emails.test')
->from($address, $name)
Helpers:
private function asJSON($data)
{
$json = json_encode($data);
$json = preg_replace('/(["\]}])([,:])(["\[{])/', '$1$2 $3', $json);
return $json;
}
private function asString($data)
{
$json = $this->asJSON($data);
return wordwrap($json, 76, "\n ");
}
Might be useful to someone.
I have the following code which sends a passowrds recovery mail:
public function recovery(Request $request)
{
$validator = Validator::make($request->only('email'), [
'email' => 'required'
]);
if($validator->fails()) {
throw new ValidationHttpException($validator->errors()->all());
}
$response = Password::sendResetLink($request->only('email'), function (Message $message) {
$message->subject(Config::get('boilerplate.recovery_email_subject'));
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->response->noContent();
case Password::INVALID_USER:
return $this->response->errorNotFound();
}
}
Which I found out uses the following template: resources/views/auth/emails/password.php
which is an empty file.
How I can access the token from this template?
Isn't there any built-in view to use from laravel?
The function in your questions doesn't return a view.
Also, I'm unfamiliar with that path to the view that is in your question. Which version of Laravel are you using?
Anyhow, you can get the reset token from the DB, just like any other value in the DB. E.g. from a controller that is returning a view:
$user = User::find(Auth::id());
$remeber_token = $user->remember_token;
return view('to_your_view.blade.php', compact('remember_token');
And then in the view file:
{{ $remember_token }}
This will output it, no need to use echo or anything.
But, again, the function you pasted into your question is not a function that is returning a view, so I'm not sure where to tell you to put the above code.
As for your questoin about Laravel having an in-built view for 'this', in Laravel 5.3, at least, the view I assume you want will be within `resources/views/auth/passwords/'.