I am trying to send a mail to a user but also want to attach a file to the mail. I am using the pdf package barryvdh/laravel-dompdf but I keep getting this error
Call to a member function attachData() on null at /app_path/app/Nova/Actions/SendAccountStatement.php:86)
This is my code
$data = [...];
$pdf = PDF::loadView('account-statement', $data);
// send account statement notification
Mail::to($model->email)
->bcc('another#mail.com')
->send(new StatementOfAccount($model)
->attachData($pdf->output(), "Account_Statement.pdf", ['mime' => 'application/pdf']);
The line throwing the error is ->attachData($pdf->output(), "Account_Statement.pdf", ['mime' => 'application/pdf'])
So from the error, I seem to missing something. What is the right way to attach a pdf file to the email?
app/Http/Controllers/TestController.php
namespace App\Http\Controllers;
use App\Mail\CheckUser;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use PDF;
class TestController extends Controller
{
public function index()
{
return view('welcome');
}
public function daily_report(Request $request)
{
$start_date = Carbon::parse($request->start_date)
->toDateTimeString();
$end_date = Carbon::parse($request->end_date)
->toDateTimeString();
$data['users'] = User::whereBetween('created_at',[$start_date,$end_date])->get();
$data['start_date'] = Carbon::parse($request->start_date)
->toDayDateTimeString();
$data['end_date'] = Carbon::parse($request->end_date)
->toDayDateTimeString();
$count = User::whereBetween('created_at',[$start_date,$end_date])->count();
if( $count < 1 ) {
session()->flash('message','There is no user between those date!');
return redirect()->back();
}
$pdf = PDF::loadView('test', $data, [
'format' => 'A4'
]);
\Mail::send('test', $data, function($message) use ($pdf){
$message->from('info#test.com*');
$message->to('mail#codechief.org');
$message->subject('Date wise user report');
$message->attachData($pdf->output(),'document.pdf');
});
$pdf->SetProtection(['copy', 'print'], '', 'pass');
return $pdf->stream('document.pdf');
}
}
One is for form and the other is our generated pdf file. So create it.
resources/views/welcome.blade.php
#extends('layouts.app')
#push('style')
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
#endpush
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
#if(session()->has('message'))
<p class="btn btn-success btn-block btn-sm custom_message text-left" style="margin-top: 10px;">{{ session()->get('message') }}</p>
#endif
<legend>Search date wise user</legend>
<form action="{{ route('report') }}" method="get">
<div class="col-md-3">
<div class="form-group">
<label for="">Start Date</label>
<input type="date" class="form-control" name="start_date">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="">End Date</label>
<input type="date" class="form-control" name="end_date">
</div>
</div>
<div class="col-md-2" style="margin-top: 24px;">
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
Related
Hello friends
I'm a new in laravel framework am trying to build a crud app so got this issue When i click Edit btn in the index page which calls data in specific ID to edit it well it shows "error 404 page not found" i still can't find where the problem is so please help
Product controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\product;
use Illuminate\Support\Facades\DB;
/*call product by specific id to update */
public function edit($id){
$product = DB::table('products')->where('id',$id)->first();
return view('product.edit',compact('product'));
}
/* product update */
public function update(request $request ,$id){
$oldlogo = $request->old_logo;
$data = array();
$data['product_name'] = $request->product_name;
$data['product_code'] = $request->product_code;
$data['product_details'] = $request->product_details;
$image = $request->file('product_logo');
if ($image){
unlink($oldlogo);
$image_name = date('dmy_H_s_i');
$ext = strtolower($image->getClientOriginalExtension());
$image_full_name = $image_name.'.'.$ext;
$upload_path = 'public/media/';
$image_url = $upload_path.$image_full_name;
$data['product_logo'] = $image_url;
$success =$image->move($upload_path,$image_full_name);
$data['product_logo'] =$image_url;
$product = DB::table('products')->where('id'.$id) -> update($data);
}
return redirect()->route('product.index')
->with('success','Product updated successfully');
}
edit btn`
<a class="btn btn-primary" href="{{ URL :: to ('edit/product'.$pro->id) }}">Edits</a>
edit page
#extends('product.layout')
#section('content')
<br><br><br>
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
</div>
<br><br><br>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('product.index') }}">Back</a>
</div>
<form action="" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-row">
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong>Product name</strong>
<input type="text" name="product_name" calss="form-control" value="{{ $product ->product_name }}">
</div>
</div>
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong>Product Code</strong>
<input type="text" name="product_code" calss="form-control" value="{{ $product ->product_code }}">
</div>
</div>
<div class="col-xs-12 col-xm-12 col-md-12">
<div class="form-group">
<strong> Detials </strong>
<textarea class="form-control" name="Details" style="height:150px" >
{{ $product ->product_details" }}</textarea>
</div>
<div class="col">
<div class="form-group">
<strong>Product image</strong>
<input type="file" name="logo">
</div>
</div>
<div class="col">
<div class="form-group">
<strong>Product old image</strong>
<img src ="{{ URL::to($product->product_logo) }}" height="70px" width="80px" alt="logo">
<input type="hidden" name=" old_logo" value="{{ $product->product_logo }}">
</div>
</div>
<button type="button" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
** edit Route **
Route::get('edit/product/{id}','ProductController#edit');
Route::post('update/product/{id}','ProductController#update');
laravel Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product extends Model
{
protected $fillable = [
'product_name', 'product_details', 'product_code','product_logo'
];
}
I think your problem is right here: {{ URL :: to ('edit/product'.$pro->id) }} because its going to print for example this: /edit.product23. What you want is /edit/product/23, so change your URL to {{ URL::to('edit/product/'.$pro->id) }} or {{ url('edit/product/'.$pro->id) }}. Also make sure you set the route like this Route::get('/edit/product/{id}, 'ControllerName#edit'); in your web.php route file.
So i was trying to make a posting form using ckeditor and post it to database, and then try to display it in the same view, but after i submit the form i don't see anything in my database table so clearly it's not even storing to database, is there any mistakes in my controller or view ?
this is my GuestbookController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Guestbook;
class GuestbookController extends Controller
{
public function index()
{
$guestbooks = Guestbook::get();
return view('post.post_textarea',[
'guestbooks' => $guestbooks,
]);
}
public function store(Request $request)
{
Guestbook::create([
'name' => $request->name,
'message' => $request->message
]);
return redirect()->back();
}
}
this is my routes
Route::get('/posting','GuestbookController#index')->name('guestbook');
Route::post('/posting','GuestbookController#store')->name('guestbook.store');
this is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Guestbook extends Model
{
protected $fillable = ['name', 'message'];
}
and this is my view
<section class="games-single-page">
<div class="container">
#foreach ($guestbooks as $guestbook)
<div class="card">
<div class="card-body">
<label>mike</label>
<h3>{{ $guestbok->name }}</h3>
{!! $guestbook->message !!}
</div>
</div>
#endforeach
<div class="card">
<div class="card-body">
<form action="/posting" method "POST">
<div class="form-group">
<label style="color: black;" >Title</label>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<label style="color: black;" >Your Input</label>
<br>
<textarea class="form-control" name="message" id="" rows="10"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value"Send">
</div>
</form>
</div>
</div>
</div>
</section>
You forgot an equal sign '=' and a csrf field. try the answer.
<form action="/posting" method="POST">
{{csrf_field()}}
Basically, I want to solve this error
Call to a member function comments() on null
I am trying to make a system on my site whereby users can post,view post comment on posts and reply.
When a user comments on http://127.0.0.1:8000/post/show/6 for example,it is meant to go to http://127.0.0.1:8000/comment/store insert the comments into the database and then show the comments
BUT
what currently happens is that after typing the comment in http://127.0.0.1:8000/post/show/6 it directs to http://127.0.0.1:8000/comment/store it show this error on laravel'S PrettyPageHandler:
Call to a member function comments() on null
I have no clue what I'm doing wrong.
Please help
These are my code:
PostController.php
<?php
// PostController.php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Auth;
use Stevebauman\Location\Facades\Location;
class PostController extends Controller
{
protected $fillable = [
'Uploader',
];
public function __construct()
{
return $this->middleware('auth');
}
public function create()
{
return view('post');
}
public function store(Request $request)
{
{
$post = new Post;
$post->title = $request->get('title');
$post->type = $request->get('type');
$post->description = $request->get('description');
$post->body = $request->get('body');
$post->UniqueId = str_random(16);
$post->Uploader = Auth::user()->name;
$post->Language = 'en';
$post->Location=Location::get()->countryCode;
$post->views = 0;
$post->Applauds = 0;
$post->Boos = 0;
$post->Tags = "hey";
if ($request->get('agegroup')) {
$post->agegroup = $request->get('agegroup');
} else {
$post->agegroup ='undefined';
}
$post->AllowComments = 'true';
$post->CommentsBg = 'default';
$post->Visibility = 'globally public';
$post->others = 'embeddable';
$post->save();
return redirect('posts');
}
}
public function index()
{
$posts = Post::all();
return view('index', compact('posts'));
}
public function show($id)
{
$post = Post::find($id);
return view('show', compact('post'));
}
}
CommentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use App\Post;
class CommentController extends Controller
{
public function store(Request $request)
{
$comment = new Comment;
$comment->body = $request->get('comment_body');
$comment->user()->associate($request->user());
$post = Post::find($request->get('post_id'));
$post->comments()->save($comment);
return back();
}
}
Web.php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('logout', '\App\Http\Controllers\Auth\LoginController#logout');
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin', 'AdminController#index')->name('admin');
Route::get('/upload', 'UploadController#index')->name('upload');
Route::get('/post/create', 'PostController#create')->name('post.create');
Route::post('/post/store', 'PostController#store')->name('post.store');
Route::get('/posts', 'PostController#index')->name('posts');
Route::get('/post/show/{id}', 'PostController#show')->name('post.show');
Route::post('/comment/store', 'CommentController#store')->name('comment.add');
Route::post('/reply/store', 'CommentController#replyStore')->name('reply.add');
Route::match(['get', 'post'], 'imageupload', 'ImageController#Image');
Route::delete('delimage/{filename}', 'ImageController#Image');
post.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Post</div>
<div class="card-body">
<form method="post" action="{{ route('post.store') }}">
<div class="form-group">
#csrf
<label class="label">Post Title: </label>
<input type="text" name="title" class="form-control" required/>
</div>
<label class="label">Post Type </label>
<input type="text" name="type" class="form-control" required/>
<label class="label">Tags </label>
<input type="text" name="tags" class="form-control" required/>
<label class="label">Age-group(optional) </label>
<input type="text" name="agegroup" class="form-control" required/>
<div class="form-group">
<label class="label">Post Description </label>
<textarea name="description" rows="5" cols="20" class="form-control" required></textarea>
</div>
<div class="form-group">
<label class="label">Post Body: </label>
<textarea name="body" rows="10" cols="30" class="form-control" required></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
show.blade.php
<!-- show.blade.php -->
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<p><b>{{ $post->title }}</b></p>
<p>
{{ $post->body }}
</p>
<hr />
<h4>Display Comments</h4>
#foreach($post->comments as $comment)
<div class="display-comment">
<strong>{{ $comment->user->name }}</strong>
<p>{{ $comment->body }}</p>
</div>
#endforeach
<hr />
<h4>Add comment</h4>
<form method="post" action="{{ route('comment.add') }}">
#csrf
<div class="form-group">
<input type="text" name="comment_body" class="form-control" />
<input type="hidden" name="post_id" value="{{ $post->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-warning" value="Add Comment" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<table class="table table-striped">
<thead>
<th>ID</th>
<th>Title</th>
<th>Action</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{ $post->Id }}</td>
<td>{{ $post->title }}</td>
<td>
Show Post
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
I guess the problem is in this part of the CommentController.php code:
$post = Post::find($request->get('post_id'));
$post->comments()->save($comment);
Your assumption is that in the first line Post::find() returns a new Post object. Clearly it doesn't. Why? I can't tell, but probably because the ID doesn't exist?
You could check for this by doing:
$post = Post::find($request->get('post_id'));
if (!is_object($post)) echo "Yeah, I really have a problem here...";
$post->comments()->save($comment);
hi this is because you're not retrieving the inputs correctly ..
class CommentController extends Controller
{
public function store(Request $request)
{
$comment = new Comment;
$comment->body = $request->comment_body;
$comment->user()->associate($request->user());
$post = Post::find($request->post_id);
$post->comments()->save($comment);
return back();
}
}
instead of using $request->get('field_name') just use $request->field_name
EDIT NOTES:
your form method is post .. you might as well use $request->post('field_name') if that function exists .. there are lot of ways to retrieve inputs but as written in my answer i used $request->field_name ..
and why you're getting that error is because the Post::find(null/undefined) returns null ..
You have this error because when you do:
$post = Post::find($request->get('post_id'));
You find nothing, so $post is null. Thus you should find out why. Try to debug and see what $request->get('post_id') contains. Maybe it contains the wrong post id or maybe it has nothing inside of it.
If that the case I think the answer would be to do:
$post = Post::find($request->input('post_id'));
Regards
I got it.
I HAD TO CHANGE post_id to post_Id` and vice-versa as in:
CommentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comment;
use App\Post;
class CommentController extends Controller
{
public function store(Request $request)
{
$comment = new Comment;
$comment->body = $request->comment_body;
$comment->user()->associate($request->user());
$post = Post::find($request->post_id);
$post->comments()->save($comment);
return back();
}
}
And in
show.blade.php
<!-- show.blade.php -->
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-body">
<p><b>{{ $post->title }}</b></p>
<p>
{{ $post->body }}
</p>
<hr />
<h4>Display Comments</h4>
#foreach($post->comments as $comment)
<div class="display-comment">
<strong>{{ $comment->user->name }}</strong>
<p>{{ $comment->body }}</p>
</div>
#endforeach
<hr />
<h4>Add comment</h4>
<form method="post" action="{{ route('comment.add') }}">
#csrf
<div class="form-group">
<input type="text" name="comment_body" class="form-control" />
<input type="hidde" name="post_id" value="{{ $post->Id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-warning" value="Add Comment" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I am trying to validate the form data as they do in laravel's default authentication. It worked few days ago but now it doesn't work. If user didn't make any mistakes in form and submit it, then it successfully save data in the db. If user submit an empty form without any data or did some mistake in the form it's not showing the error message. If i add controller function code in a try catch, exception is showing as 'Invalid data'
view(form)
<form class="form-horizontal" action="{{ route('save-service-page-content') }}" method="POST" enctype="multipart/form-data">
<div class="box-body">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('file') ? ' has-error' : '' }}">
<label for="image" class="col-sm-2 control-label">Service Image</label>
<input hidden id="service_image_file" name="file"/>
<div class="col-sm-10" id="demo-upload">
<div class="dropzone needsclick dz-clickable" id="serviceImageUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
#if ($errors->has('file'))
<span class="help-block"><strong>The service image is reuired</strong></span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="inputEmail3" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea rows="8" class="form-control" name="description" placeholder="Description goes here"></textarea>
#if ($errors->has('description'))
<span class="help-block"><strong>{{ $errors->first('description') }}</strong></span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description_sin') ? ' has-error' : '' }}">
<label for="inputEmail3" class="col-sm-2 control-label">හැදින්වීම</label>
<div class="col-sm-10">
<textarea rows="8" class="form-control" name="description_sin" placeholder="හැදින්වීම සිංහලෙන්"></textarea>
<small class="form-text text-muted">හැදින්වීම ඇතුලත් කරන්න. (හැදින්වීම සිංහල බසින් ඇතුලත් කලොත් පමණක් එය ඉංග්රීසි බස වෙනුවට සිංහල බසින් දිස්වනු ඇත.)</small>
#if ($errors->has('description_sin'))
<span class="help-block"><strong>මෙම හැදින්වමෙහි අක්ෂර සහ ඉලක්කම් පමණක් ඇතුලත් විය යුතුය </strong></span>
#endif
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer clearfix">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
</form>
Controller
namespace App\Http\Controllers;
use App\Service_page_content;
use App\Service;
use File;
use Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ServiceContent extends Controller
{
protected function validator(array $data)
{
return Validator::make($data, [
'file' => 'required',
'description' => 'nullable|alpha_num_spaces_brackets',
'description_sin' => 'nullable|alpha_num_spaces_brackets',
]);
}
public function save_page_content(Request $request)
{
$this->validator($request->all())->validate();
$service_page_content = new Service_page_content;
$service_page_content->description = $request->description;
$service_page_content->description_sin = $request->description_sin;
$file = $request->file;
$image_decode = base64_decode($file);
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = "service-page-content-".time().'.'.str_replace("image/","",$mime_type);
$image_resized = Image::make($image_data);
$image_resized->resize(1170, null, function ($constraint) {
$constraint->aspectRatio();
});
$image_resized->save(public_path("uploads/service_page_content_uploads/$imageName"));
$service_page_content->main_img_url = $imageName;
$service_page_content->save();
return redirect()->back()->with('success', ['Data Saved']);
}
}
I don't know if I'm doing it correctly on return Validator::make($data,...... or $this->validator($request->all())->validate();
I have written a custom validation rule that allows alpha numeric, spaces, brackets, '.' and ',' in AppServiceProvider boot function. It also worked few days ago. Now nothing seems to work.
It worked few days ago. Ignore the file upload part it is working perfectly I'm using Dropzone.js for it. May be I'm missing something. Any help would be appreciated !
You can validate directly on the array without calling the Validator facade.
protected function validator(Request $request)
{
return $request->validate([
'file' => 'required',
'description' => 'nullable|alpha_num_spaces_brackets',
'description_sin' => 'nullable|alpha_num_spaces_brackets',
]);
}
public function save(Request $request){
$this->validator($request);
}
When I update my comment it goes back to the page and changes the comment back to orignal, so the update hasn't been done. No errors or something.
db: comments
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('articleID')->unsigned();
$table->string('comment');
$table->timestamps();
});
model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = ['comment', 'articleID'];
public function article() {
return $this->belongsTo('App\Article');
}
}
CommentsController
public function edit($commentID) {
$comment = Comment::findOrFail($commentID);
return view('pages.comments.edit', compact('comment'));
}
public function update($commentID, CommentRequest $request) {
$comment = Comment::findOrFail($commentID);
$comment->update($request->all());
return view('/');
}
editComment view
<form action="{{ route('updateComments', ['commentID' => $comment->id]) }}" class="form-horizontal" method="get">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<!-- Article data -->
<div class="form-group">
<label class="col-sm-3 control-label" for="body">Comment</label>
<div class="col-sm-6">
<textarea class="form-control" id="body" name="body" maxlength="1000">{{ $comment->comment }}</textarea>
</div>
</div>
<!-- Add Article Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-default" type="submit"><i class="fa fa-pencil-square-o"></i> Edit comment</button>
</div>
</div>
</form>
Your problem is:
You cannot do form submit with get method, even with hidden method_field('PATCH') in fact it does not event get to update action (:
Your form field name body is not correct if we look at fillable field of model
So just fix Your form:
<form
action="{{ route('updateComments', ['commentID' => $comment->id]) }}"
method="post"
class="form-horizontal">
{{ csrf_field() }}
<!-- Article data -->
<div class="form-group">
<label class="col-sm-3 control-label" for="comment">Comment</label>
<div class="col-sm-6">
<textarea
id="comment"
name="comment"
maxlength="1000"
class="form-control"
>{{ $comment->comment }}</textarea>
</div>
</div>
<!-- Add Article Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-default" type="submit">
<i class="fa fa-pencil-square-o"></i> Edit comment
</button>
</div>
</div>
</form>
or change Your schema and model to have field called body not comment
p.s. also fix Your update action:
public function update(CommentRequest $request, $commentID) {
$comment = Comment::findOrFail($commentID);
$comment->update($request->except(['articleID'])); // for safety we are ignoring "possible existence" of articleID in forma
return redirect(route('updateComments', compact('commentID')));
}
doing return view('/') is not correct - it's trying to find file with name / that of course does not exist.