Send pdf file as email attachment in laravel 5.7 - laravel

I want to send email of invoice blade file as pdf but i getting following error
(1/1) Swift_IoException
Unable to open file for reading [/storage/D:\xampp\htdocs\clientreq\public/mypdf.pdf]
controller:
public function insert(Request $req)
{
ini_set('max_execution_time', 300000);
$mytime = Carbon::now();
$project_type=implode(',',$req->input('project_type'));
//$qty=implode(',',$req->input('qty'));
$amount=implode(',',$req->input('amount'));
$id=$req->input('id');
$bill_date=$req->input('bill_date');
$updated_at=$mytime->toDateTimeString();
$created_at=$mytime->toDateTimeString();
$data = array('client_id'=>$id,'date_of_bill'=>$bill_date,'description'=>$project_type,'amount'=>$amount,'created_at' => $created_at,'updated_at' => $updated_at);
DB::table('bill')->insert($data);
$client = DB::table('requirement')
->join('bill','requirement.id','=','bill.client_id')
->select('requirement.*','bill.*')
->where('requirement.id',$id)
->where('bill.date_of_bill',$bill_date)
->first();
$data = array(
'client_name' => $client->client_name,
'company_name' => $client->company_name,
);
$pdf = \PDF::loadView('pages.invoice',$data);
//return $pdf->stream();
$data = array(
'email_address'=>'seemashelar01#gmail.com',
);
Mail::send('pages.invoice', $data, function($message) use($data) {
$message->from('seemashelar01#gmail.com', 'PuraBox');
$message->to($data['email_address']);
$message->subject('hello');
$filename = \Storage::url(public_path() . '/' . 'mypdf.pdf');
$message->attach($filename);
//Full path with the pdf name
});
}

if you want address file from Storage you should call attachFromStorage , like this:
$message->attachFromStorage(
/path/to/file',
'name.pdf', [
'mime' => 'application/pdf'
]);
more info : https://laravel.com/docs/5.7/mail#attachments

Try this bellow example thats it
$data = array(
'name' => Input::get('name'),
'detail'=>Input::get('detail'),
'sender' => Input::get('sender')
);
$pdf = PDF::loadView('letters.test', $data);
Mail::send('emails.invoice', $data, function($message) use($pdf)
{
$message->from('us#example.com', 'Your Name');
$message->to('foo#example.com')->subject('Invoice');
$message->attachData($pdf->output(), "invoice.pdf");
});

Related

upload image in laravel 8 - API

I want to upload image for my posts and have polymorphism relation one to one (because I have other tables and they need image too ) between posts and images
And when I want to send request and store the image in database , I get this error:
BadMethodCallException: Call to undefined method App\Models\Image::move()
I'm creating an API so :
My postman :
My relations :
Image model :
class Image extends Model
{
use HasFactory;
protected $fillable = [
'image'
];
public function imageable(){
return $this->morphTo();
}
}
Post model :
class Post extends Model
{
use HasFactory;
use \Conner\Tagging\Taggable;
protected $fillable = [
'user_id' ,
'category_id' ,
'title' ,
'body' ,
'study_time',
'likes',
'status',
'tags',
];
public function image(){
return $this->morphOne(Image::class , 'imageable');
}
}
And the PostController , store() method :
public function store(Request $request )
{
$data = $request->all();
$validator = Validator::make($data, [
'user_id'=>'required',
'category_id'=>'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time'=>'required',
'tags'=>'nullable|string',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'error']);
}
//separate tags
$tags = explode(",", $request->tags);
$image = new Image;
$getImage = $request->file('image');
$imageName = time().'.'.$getImage->extension();
$image->move(public_path('images'), $imageName);
$post = Post::create($data);
$post->image()->save($image);
//save tags
$post->tag($tags);
return response()->json([
"success" => true,
"message" => "successfull",
"data" => $post
]);
}
Where is my mistake?
After a month of this challenge, I was finally able to solve it :}
To make the code better and cleaner, I added another column to my image table : path
it's for saving path of image , and another column : image
and i added the path to my fillable in Image model and i edited the code to this :
public function store(Request $request )
{
$data = $request->all();
$validator = Validator::make($data, [
'user_id'=>'required',
'category_id'=>'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time'=>'required',
'tags'=>'nullable|string',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'error']);
}
//separate tags
$tags = explode(",", $request->tags);
$image = new Image;
$getImage = $request->image
$imageName = time().'.'.$getImage->extension();
$imagePath = public_path(). '/images/posts';
$image->path = $imagePath;
$image->image = $imageName;
$getImage->move($imagePath, $imageName);
$post = Post::create($data);
$post->image()->save($getImage);
$post->tag($tags);
return response()->json([
"success" => true,
"message" => "successfully",
"data" => $post
]);
}

How to access property of an object in Laravel PHP?

I am having 2 methods. In one of the method I am making a call to database, a pure and simple one Document::findOrFail($data->id). But this is always returning me null although a record is already persisted. Any idea how to get this simple thing sorted?
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
public function downloadlockExport($token)
{
try {
$data = (object) Cache::get($token);
// dd I get the full $data as object
$document = Document::findOrFail($data->id);
// undefined. Above query did not execute.
// Thus, below query failed
$document->update(['downloads' => $document->downloads + 1]);
$content = Crypt::decrypt(File::get($data->file));
return response()->make($content, 200, array(
'Content-Disposition' => 'attachment; filename="' . basename($data->file) . '"'
));
} catch (\Exception $e) {
\App::abort(404);
}
}
What you probably would like to do is:
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
$token = 'mytoken';
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
This way you will get your $token in your called function and you will get the $data correctly as I see.
And in the downloadlockExport() function you will have the ID like this:
$document = Document::findOrFail($data->mytoken['id']);
or you can use:
$document = Document::findOrFail($data->$token['id']);
similar with getting the File value:
$content = Crypt::decrypt(File::get($data->$token['file']));

getting error when i update image in my admin panel

I want to update my product table but when I update my product table, it throws this error :
ErrorException in CreatesController.php line 201: Undefined variable:
name
201 line is this: 'image'=> $name,
My product table contains following fields :
productname,image,price,category_id
This is CreatesController :
public function productupdate(Request $request, $id){
$this->validate($request, [
'productname'=>'required',
'image'=>'image|mimes:jpg,png,jpeg|max:10000',
'price'=>'required',
'category_id'=>'required'
]);
if($request->hasfile('image'))
{
$file=$request->file('image');
$new_name = rand(). '.' .
$path=public_path().'/images';
$name=$file->getClientOriginalName();
$file->move($path, $name);
$data=$name;
}
$data=array(
'productname'=> $request->input('productname'),
'image'=> $name,
'price'=> $request->input('price'),
'category_id'=> $request->input('category_id')
);
Product::where('id', $id)
->update($data);
return redirect('/item')->with('info','Product updated successfuly!');
}
If you are only updating the product details without uploading an image, then if($request->hasfile('image')) becomes false, as $name variable is not getting assigned. Try this..
public function productupdate(Request $request, $id) {
$this->validate($request, [
'productname' => 'required',
'image' => 'image|mimes:jpg,png,jpeg|max:10000',
'price' => 'required',
'category_id' => 'required'
]);
$data = array(
'productname' => $request->input('productname'),
'image' => null,
'price' => $request->input('price'),
'category_id' => $request->input('category_id')
);
if ($request->hasfile('image')) {
$file = $request->file('image');
$path = public_path() . '/images';
$name = $file->getClientOriginalName();
$file->move($path, $name);
$data['image'] = $name;
}
Product::where('id', $id)
->update($data);
return redirect('/item')->with('info', 'Product updated successfully!');
}

Laravel Uploading a photo

Hi i am trying to upload a photo but i do not get the filename of the photo in my database..The photo successfully uploads to my folder.i have this in my controller
public function postCreatePost(Request $request)
{
if ($request->hasFile('avatar'))
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save( public_path('uploads/posts/' .$filename));
Auth::user()->posts()->create([
'body' => $request->body,
'username' => Auth::user()->name,
'photo' => $filename,
]);
$posts = Post::orderBy('created_at', 'desc')->get();
return view('home', ['post' => $posts]);
}
Can anyone please tell me what i am missing

Cannot upload file using guzzle and send to laravel API

I have two laravel projects, one for API and one for front end. What I want to achieve is to send the uploaded file on my front end and send it to my API using guzzlehttp6. Here's my code.
FrontEnd Laravel:
public function store(Request $request, $module_id)
{
$videos = $request->file('file');
// $name = time().$videos->getClientOriginalName();
// $path = ('videos');
// $videoFinal = $videos->move($path, $name);
$file_name = fopen($videos, 'r');
$client = new Client(['base_uri' => 'http://localhost/api.kourse/public/api/v1/']);
try{
$response = $client->request('POST', 'modules/'.$module_id.'/videos',[
'file_name' => $file_name
]);
}catch(ClientException $e){
return $e->getResponse();
}
}
When returning the $videos im getting the path of the file.
Here's my API
public function store(VideoRequest $request, $moduleId)
{
$module = Module::find($moduleId);
if( !$module )
{
return response()->json([
'message' => 'Module does not exist',
'code' => 404
],404);
}
$file = $request->file('file_name');
$name = time(). $file->getClientOriginalName();
$path = '/videos';
$file->move(public_path().$path, $name);
Video::create([
'file_name' => $name,
'file_path' => $path.$name,
'module_id' => $module->id
]);
return response()->json([
'message' => 'Successfully created and assgin video to this module'
],200);
}
What Iam getting is that :
{message: {file_name: ["The file name field is required."]}, code: 422}
code
:
422
as defined in my VideoRequest.
Can anyone help me on this.

Resources