Can't access data in email view - laravel

I have a problem with email's views with Laravel. This is how I send a mail:
$user = $bet->user; // A bet hasOne user. All is ok here
Mail::queue('emails.betWon', array('user' => $user), function($message) use ($user)
{
$message->to($user->email)->subject('Tu as remporté un pari !');
});
This is my view emails.betWon:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
</head>
<body>
{{ var_dump($user) }}
</body>
</html>
And this is the mail I get:
array (size=3)
'timestamps' => boolean false
'incrementing' => boolean true
'exists' => boolean true
Which is not a User object...

Because you are using Mail::queue you cannot send an object to the queue, as data is being serialized. You need to convert it to an array first.
change
$user = $bet->user;
to
$user = $bet->user->toArray();

Related

$message is undefined on laravel 8

I'm learning Laravel, and I've been trying to pass data between a controller and a view, but I'm still getting the same error on the page. Does anyone know how to fix this? Even with this small code, it doesn't seem to work. Do I need to make a configuration or something?
I've tried
->with('message', 'Hi Victoria')
view
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>App title</title>
<html>
<body>
<h1>Hello, {{ $message }}</h1>
</body>
</html>
</html>
controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Hello;
class HelloWorld extends Controller
{
public function sayHello()
{
return view('hello', ['message' => 'Hi Victoria']);
}
}
web.php
Route::get('/', function(){
return view('hello');
});
The problem is that you have written a controller, but you are not using it. In your route ( web.php ), you have returned the view.
You should take a look at Laravel's documentation regarding how to make a route point to a controller method
So, you would need to change your route in web.php to
use App\Http\Controllers\HelloWorld;
Route::get('/', [HelloWorld::class, 'sayHello']);
In web.php, you should write the following code to use the HelloWorld controller:
use App\Http\Controllers\HelloWorld;
Route::get('/', [HelloWorld::class, 'sayHello']);
you can try this in web.php
Route::get('/', function(){
return view('hello',['message' => 'Hi Victoria']);
});

Chartisan/Laravel - > "Call to undefined method" error

I am trying to figure out how to use Chartisan and my controllers in Laravel. Having spend a couple of days on this, I have to admit that I am missing some fundamental because I understand the error, I just can't fix it..
What I have done so far is followed this https://charts.erik.cat/guide/installation.html#publish-the-configuration-file and reading multiple other guides online on how to solve it. If I stick to the guide, with the basic example then it works fine, but I want to create multiple charts, based on id/user variables which require I get the information from my database..
My problem is: "Call to undefined method App\Charts\SampleChart::labels()"
Are there anyone who has experience with this issue and tell me how to fix?
SampleChart.php (location: app/Charts/SampleChart.php)
declare(strict_types = 1);
namespace App\Charts;
use Chartisan\PHP\Chartisan;
use ConsoleTVs\Charts\BaseChart;
use Illuminate\Http\Request;
class SampleChart extends BaseChart
{
/**
* Handles the HTTP request for the given chart.
* It must always return an instance of Chartisan
* and never a string or an array.
*/
public ?string $name = 'my_chart';
public ?string $routeName = 'my_chart';
public function handler(Request $request): Chartisan
{
return Chartisan::build();
}
}
My Controller is:
namespace App\Http\Controllers;
use App\Charts\SampleChart;
use App\Charts\ExerciseInsight;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ExerciseInsightChartController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request): Chartisan
{
$samplechart = new Samplechart;
$exercise = 16;
$created_at = [];
$exercise_name = [];
$exercise_weight = [];
$exercise_rep = [];
$records = DB::table('dump_all_records')->where('exercise_id',"=", $exercise)->get();
foreach ($records as $record)
{
array_push($created_at, $record->created_at);
array_push($exercise_name, $record->exercise_name);
array_push($exercise_weight, $record->exercise_unit_value);
array_push($exercise_rep, $record->exercise_round_value);
}
// dd($samplechart);
$samplechart->labels($created_at);
$samplechart->dataset(['Weight','line', $exercise_weight]);
// $samplechart->dataset('Reps','line', $exercise_rep);
return view('insight.exercise_insight', compact('samplechart'));
}
}
my view is:
<!-- Charting library -->
<script src="https://unpkg.com/echarts/dist/echarts.min.js"></script>
<!-- Chartisan -->
<script src="https://unpkg.com/#chartisan/echarts/dist/chartisan_echarts.js"></script>
<!-- Chart's container -->
<div id="chart" style="height: 300px;"></div>
<script>
const chart = new Chartisan({
el: '#chart',
url: "#chart('my_chart')",
hooks: new ChartisanHooks()
.colors(['#4299E1','#FE0045','#C07EF1','#67C560','#ECC94B'])
// .datasets([{ type: 'line', fill: false }, 'bar'])
.datasets(
[
{
type: 'line',
fill: true ,fillColor : 'rgba(38,198,218,1)',
strokeColor : 'rgba(38,198,218,0)',
pointColor : '#26c6da',
pointStrokeColor : 'rgba(38,198,218,0)',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(38,198,218,1)',
},
{
type: 'line',
fill: true
}
]
)
.axis(true)
.tooltip()
});
</script>
Since the documentation has wroten, you can pass the data manually using data : {...} property.
So, the first step is call the Chartisan class, but don't forget to call the ServerData Class first, because the Chartisan Class constructor need parameter a ServerData Class.
In YourController.php
use Chartisan\PHP\Chartisan;
use Chartisan\PHP\ServerData;
In your method,
public function index () {
$serverdata = new ServerData;
$chart = new Chartisan($serverdata);
$chart->labels(
['First', 'Second', 'Third', 'Four', 'Five',
'Six', 'Seven', 'Eight', 'Nine', 'Ten']);
/**
* This your query will be placed,
* just for example :
*/
for ($i = 1; $i < mt_rand(5,9); $i++) {
$chart->dataset('Attribute '. $i, [
mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50),
mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50), mt_rand(3,50)
]);
}
/**Please remember on this chartisan version,
* Chartisan class will return an Object
* But the frontend loader just read a JSON format only.
* so it's easily to call Chartisan toJSON method.
* */
$chart = $chart->toJSON();
return view('your.view', [
'chart' => $chart,
]);
}
Next, in your blade view, this must be same scheme to load the chart according the documentation. But don't forget to escape $chart variable at blade syntax.
<script>
const chart = new Chartisan({
el: '#chart',
data: {!! $chart !!},
hooks: new ChartisanHooks()
.title({
textAlign: 'center',
left: '50%',
text: 'Example Chart Title',
})
.colors()
.datasets('line')
.axis(true)
.tooltip()
});
</script>
And the html part,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<!-- here your chart-->
<div id="chart" style="height: 300px;"></div>
</div>
</body>
</html>
CMIIW. Hope its help.
Thank you.

how to call data from laravel mailable in a view

I have a mailable class that sends an email to someone that makes a contract. Now I'm trying to style the mail but... I can't quite seem to call the variable that I pass in the mailable class return.
I've tried passing it to the view in the mailable class and I've tried calling it but in the mail it doesn't show up.
this is my mailable class:
public function build()
{
$data = array(
'comapny' => $this->data['company'],
'file' => $this->data['file'],
'subject' => $this->data['subject'],
'email' => $this->data['email']
);
foreach($data['email'] as $mail)
return $this->view('mails.contract')->with('data' , $data['company'])->to($mail)->subject($data['subject'])->attach($data['file'])->withSwiftMeassage(function ($message){
$swiftMessage = $message->getSwiftMessage();
$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('From', 'example - contract <example-email#gmail.com>');
$headers->addTextHeader('Reply-To', 'example-email#gmail.com');
$headers->addTextHeader('X-Mailer:', 'PHP/' . phpversion());
});
}
}
the view i need to call the data to:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p><?php echo $data ?></p>
</body>
</html>
any help is appreciated
You need to use with() with arrays.
Replace ->with('data' , $data['company']) with ->with(['data' => $data['company']])
If you are returning a view to render data for the mail template (in this case i suppose its mails.contract template), do you have a blade template that is located in resources/mails/ and named contract.blade.php?
https://laravel.com/docs/5.8/mail#configuring-the-view
https://laravel.com/docs/5.8/mail#view-data
You can pass a variable into the mailable class like.
Need to create a constructor and define a public function.
public $data;
public function __construct( $parameter )
{
$data = /*Your logic define here and assign to `$this->data`*/
$this->data = $data;
}
public function build()
{
return $this->view('mails.contract')->with(['data' => $this->data])
->to($mail)->subject($this->data['subject'])
->attach($this->data['file'])
->withSwiftMeassage(function ($message){
$swiftMessage = $message->getSwiftMessage();
$headers = $swiftMessage->getHeaders();
$headers->addTextHeader('From', 'example - contract <example-email#gmail.com>');
$headers->addTextHeader('Reply-To', 'example-email#gmail.com');
$headers->addTextHeader('X-Mailer:', 'PHP/' . phpversion());
});
}
any public property defined on your mailable class will automatically be made available to the view.

Laravel pass parameter to email page

Under Laravel 5 i'm trying to send mail for user with this below route :
Route::post('/sendEmailToUser', array(
'as' => 'sendEmailToUser', function () {
$data = \App\User::find(Request::input('user_id'));
$cdata = array('message' => Request::input('message'), 'email' => $data->email);
Mail::send('emails.custom_email_to_user', $cdata, function ($message) use ($data) {
$message->to($data['email'], 'Sample')->subject('Sample');
});
if (count(Mail::failures()) > 0) {
Log::emergency("email dont send to user");
return 0;
} else {
Log::info("email successfull send to user id" + Request::input('user_id'));
return 1;
}
}
));
Result of $cdata is :
Array
(
[message] => this is test mail
[email] => myname#server.com
)
Unfortunately i get this error :
htmlentities() expects parameter 1 to be string, object given (View: D:\xampp\htdocs\epay-pro\resources\views\emails\custom_email_to_user.blade.php)
My simple email page is:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Sample</h2>
<div>
{{$message}}
{{ URL::to('www.epay.li') }}<br/>
</div>
</body>
</html>
You have to change two things in your code and it will work.
First : (choose how to use your variable $data)
You're using same variable $data sometimes as array and sometimes as object :
As object in :
$cdata = array('message' => Request::input('message'), 'email' => $data->email);
As array in :
$message->to($data['email'], 'Sample')->subject('Sample');
Normally you should use it as object since User::find will return an object.
Note : if you want to use it as array you have just to add toArray() after find.
Second : (change variable $message name)
Note: A $message variable is always passed to e-mail views, and allows the inline embedding of attachments. So, you should avoid passing a message variable in your view payload.
Source : Document laravel 5.1 - mail#introduction
So you have to change $message variable name because Framework will consider it as an Object of class Illuminate\Mail\Message.
Take a look to the following discution about the problem Laravel Mailing Issue "Object of class Illuminate\Mail\Message could not be conv...
Hope this helps.
While sending email $message variable seems to be conflicted with the laravels $message variable, i am not quite sure why. In your $cdata instead of message key use something else like maybe $text
$cdata = array('text' => Request::input('message'), 'email' => $data->email);

Echo data with eloquent

I am trying to get data out of my table, and send that array of output over to my view and there echo out specific parts of it.
I get an exception error: Undefined index bassengId.
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bassengweb</title>
</head>
<body>
<?php
if(isset($htt))
{
echo $htt['malingsId'];
}
?>
</body>
</html>
routes.php
Route::get('/', 'HomeController#showIndex');
Route::post('/data', 'HomeController#showInput');
homecontroller.php
public function showIndex()
{
return View::make('index');
}
public function showInput()
{
$htt = hvertredjetime::all();
return View::make('index')->with('htt', $htt);
}
If I try to just echo the $htt variable from index, I get:
[{"malingsId":1,"dato":"25.02.2014","tid":"12:44:00","frittKlor":"4.00","bundetKlor":"5.00","totalKlor":"9.00","ph":"7.00","autoPh":"8.00","autoKlor":"9.00","redox":"5.00","bassengId":1}]
I am a little stuck here, being new to this and not really seeing what I do wrong.
By using the ::all() method you are returning an array
public function showInput()
{
$htt = hvertredjetime::all();
return View::make('index')->with('htt', $htt);
}
In the View
#if(! is_null($htt))
#foreach($htt as $item)
<p>{{ $item->bassengId }}</p>
#endforeach
#endif
If you want to access data like this, you should do:
return View::make('index')->with(array('htt' => $htt));
Instead, return it like this:
return View::make('index')->with($htt);
And then, in view, access it directly:
{{ bassengId }}
You should access to the variable like this :
if(isset($htt))
{
echo $htt->bassengId;
}
or if you're using blade template :
#if(isset($htt))
{{ $htt->bassengId }}
#endif

Resources