Send attachment in laravel - php

I want to send an attachment with email. Till now I am able to send the attachment with mail but the problem is when I am downloading attachment it will show HTML code of my login page.
Please help me to figure it out why attachment show loging page data
Below is my code for compose.blade
<form class="form-horizontal" method="post" action="{{ action('ServiceRequestEmailController#store') }}" enctype="multipart/form-data">
<div class="mt20 clearfix text-right action-btn-btm">
<button class="btn btn-primary">Send</button>
<a class="btn btn-danger" href="{{ url('superadmin/service-request/view/' . $ServiceRequest->id) }}">Discard</a>
<div class=" border-bottom"></div>
</div>
{{ csrf_field() }}
<input type="hidden" name="sr_id" value="{{ $ServiceRequest->id }}">
<input type="hidden" name="parent_id" value="{{ $mail->getParentId() }}" />
<input type="hidden" name="action" value="{{ $mail->getAction() }}" />
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="email">Service Request:</label>
<div class="col-sm-8 col-md-6"><span>{{ $ServiceRequest->id }}</span></div>
</div>
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2">Consultant Name:</label>
<div class="col-sm-8 col-md-6"> <span>{{ $ServiceRequest->name }}</span> </div>
</div>
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2">Consultant Code:</label>
<div class="col-sm-8 col-md-6"> <span>{{ $ServiceRequest->mca_no }}</span> </div>
</div>
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="from">From:</label>
<div class="col-sm-8 col-md-6">
<select class="form-control" name="from">
#foreach ( $mail->from() as $email )
<option>{{ $email }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group autocomplete-to">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="to">To:</label>
<div class="col-sm-8 col-md-6">
<input type="text" class="form-control" name="to" id="to" value="{{ old('to') ?: $mail->to() }}" />
#if ($errors->has('to.*'))
<p class="error-msg">{{ $errors->first('to.*') }}</p>
#endif
</div>
</div>
<div class="form-group autocomplete-to">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="cc">Cc:</label>
<div class="col-sm-8 col-md-6">
<input type="text" class="form-control" name="cc" id="cc" value="{{ old('cc') ?: $mail->cc() }}" />
#if ($errors->has('cc.*'))
<p class="error-msg">{{ $errors->first('cc.*') }}</p>
#endif
</div>
</div>
<div class="form-group autocomplete-to">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="bcc">Bcc:</label>
<div class="col-sm-8 col-md-6">
<input type="text" class="form-control" name="bcc" id="bcc" value="{{ old('bcc') ?: $mail->bcc() }}" />
#if ($errors->has('bcc.*'))
<p class="error-msg">{{ $errors->first('bcc.*') }}</p>
#endif
</div>
</div>
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="subject">Subject:</label>
<div class="col-sm-8 col-md-6">
<input type="text" class="form-control" name="subject" value="{{ old('subject') ?: $mail->getSubject() }}" />
#if ($errors->has('subject'))
<p class="error-msg">{{ $errors->first('subject') }}</p>
#endif
</div>
</div>
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="template">Email Template:</label>
<div class="col-sm-8 col-md-6">
<select class="form-control" id="template" v-model="template" v-on:change="loadTemplate()">
<option value="">None</option>
#foreach ($templates as $template)
<option value="{{ $template->id }}">{{ $template->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="content">Email Text:</label>
<div class="col-sm-8 col-md-9">
<main>
<div class="adjoined-bottom">
<div class="grid-container">
<div class="grid-width-100">
<textarea name="content" id="editor1" rows="10" cols="80"><?php echo nl2br($mail->getBody()); ?></textarea>
</div>
</div>
</div>
</main>
#if ($errors->has('content'))
<p class="error-msg">{{ $errors->first('content') }}</p>
#endif
</div>
</div>
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="email">File Upload:</label>
<div class="col-sm-8 col-md-6">
<div class="attachments">
<input type="file" name="attachments[]" class="form-control" />
</div>
<div class="clearfix">
<button type="button" class="btn btn-primary" data-action="add-more-attachment">Add More</button>
</div>
</div>
</div>
<div> </div>
#if ($mail->getAction() == 'FORWARD' && ($mailModel = $mail->getInstance()))
<div class="gen-info mt20">
<div class="col-md-12">
<h3 class="subheading icon-open-close" data-toggle="collapse" data-target="#locale-setting">Attachments</h3>
</div>
<div class="col-md-12 collapse in" id="locale-setting">
<div class="clearfix">
<table class="table table-striped">
<thead>
<tr>
<th>Action</th>
<th>File Name</th>
</tr>
</thead>
<tbody>
#if (($attachments = $mailModel->attachments) && !$attachments->isEmpty())
#foreach ($attachments as $attachment)
<tr>
<td><a target="_blank" href="{{ url('public/attachments/' . $attachment->filename) }}" target="_blank">Preview</a></td>
<td>{{ $attachment->original_filename }}</td>
</tr>
#endforeach
#else
<tr>
<td colspan="2" align="center">No Attachments Found</td>
</tr>
#endif
</tbody>
</table>
</div>
</div>
</div>
#endif
<div class="form-group">
<label class="col-form-label example-text-input col-sm-4 col-md-2" for="email"></label>
<div class="col-sm-8 col-md-6">
<button class="btn btn-primary">Send</button>
<a class="btn btn-danger" href="{{ url('superadmin/service-request/view/' . $ServiceRequest->id) }}">Discard</a>
</div>
</div>
</form>
and code for controller
public function compose(ServiceRequest $ServiceRequest)
{
$templates = MailTemplate::where('org_id', $ServiceRequest->org_id)->get();
$mail = new Compose($ServiceRequest);
return view('admin.ServiceRequestEmails.compose')
->with(compact('ServiceRequest', 'mail', 'templates'));
}
public function reply(MailModel $mail)
{
$ServiceRequest = $mail->ServiceRequest;
$templates = MailTemplate::where('org_id', $ServiceRequest->org_id)->get();
return view('admin.ServiceRequestEmails.compose')
->with([
'templates' => $templates,
'mail' => new Reply($mail),
'ServiceRequest' => $ServiceRequest,
]);
}
public function replyToAll(MailModel $mail)
{
$ServiceRequest = $mail->ServiceRequest;
//print_r($ServiceRequest);
$templates = MailTemplate::where('org_id', $ServiceRequest->org_id)->get();
//print_r($templates);
//die();
return view('admin.ServiceRequestEmails.compose')
->with([
'templates' => $templates,
'mail' => new ReplyToAll($mail),
'ServiceRequest' => $ServiceRequest,
]);
}
public function forward(MailModel $mail)
{
$ServiceRequest = $mail->ServiceRequest;
$templates = MailTemplate::where('org_id', $ServiceRequest->org_id)->get();
return view('admin.ServiceRequestEmails.compose')
->with([
'templates' => $templates,
'mail' => new Forward($mail),
'ServiceRequest' => $ServiceRequest,
]);
}
public function store(Request $request)
{
$this->request = $request;
(new \App\Modicare\Validators\ServiceRequestEmailValidator($this->request))
->validate();
$ServiceRequest = ServiceRequest::find($request->sr_id);
$senderName = $this->getSenderNameByEmail($request->from);
$this->mail = MailModel::create([
'sr_id' => $request->sr_id,
'parent_id' => $request->parent_id,
'sender_name' => $senderName,
'from' => $request->from,
'to' => $request->to,
'cc' => $request->cc,
'bcc' => $request->bcc,
'subject' => $request->subject,
'body' => $request->content,
'mca_no' => $ServiceRequest->mca_no,
'sent_at' => date('Y-m-d H:i:s'),
'status' => 'SENT',
'type' => 'OUT'
]);
if ($request->parent_id && ($mail = MailModel::find($request->parent_id))) {
$mail->status = 'REPLIED';
$mail->save();
}
$mailSender = MailFacade::to(explode(',', $request->to));
if ($request->cc) {
$mailSender->cc(explode(',', $request->cc));
}
if ($request->bcc) {
$mailSender->bcc(explode(',', $request->bcc));
}
if (!empty($request->attachments) && is_array($request->attachments))
$files = $this->saveAttachments($request->attachments);
$this->handleForwardMail();
$mailSender->send(new ServiceRequestReply($this->mail));
return redirect('superadmin/service-request/view/' . $request->sr_id);
}
private function getSenderNameByEmail($email)
{
// $organizationEmail = OrganizationEmail::where('email', $email) -> orderBy ('id', 'desc')
//;
$organizationEmail = OrganizationEmail::where('email', $email)
->first();
if ($organizationEmail) {
return $organizationEmail->organization->getName();
}
return Auth::User()->getName();
}
public function view(MailModel $mail)
{
if ($mail->status == 'NEW') {
$mail->status = 'SEEN';
$mail->save();
}
return view('admin.ServiceRequestEmails.view', compact('mail'));
}
public function print(MailModel $mail)
{
return view('admin.ServiceRequestEmails.print', compact('mail'));
}
private function handleForwardMail()
{
if ($this->request->action == 'FORWARD' &&
($parent = $this->mail->parent)) {
foreach ($parent->attachments as $attachment) {
$newAttachment = $attachment->replicate();
$newAttachment->ref_id = $this->mail->id;
$newAttachment->save();
}
}
}
private function saveAttachments(array $attachments)
{
$files = [];
foreach ($attachments as $key => $attachment) {
$files[$key] = [
'newFilename' => $attachment->store('attachments', 'public'),
'originalFilename' => $attachment->getClientOriginalName(),
];
Attachment::create($attachment->getRealPath(),[
'type' => 'MAIL',
'ref_id' => $this->mail->id,
'original_filename' => $attachment->getClientOriginalName(),
'filename' => basename($files[$key]['newFilename']),
'extn' => $attachment->getClientOriginalExtension(),
'mime_type' => $attachment->getClientMimeType(),
'size' => $attachment->getClientSize(),
]);
}
}

Related

Update photo using Laravel

I created a table called "directors" using migrations.Then i created the model, view, controller.
In "DirectorController" i wrote crud operations logic for my table. It works until i try to edit a existing record. To be clear it update all informations except the image, it remains the same. Can someone tell me what is wrong?
*Folder "images" exists in public.
enter image description here
//Migration
public function up()
{
Schema::create('directors', function (Blueprint $table) {
$table->id();
$table->string('first_name');
$table->string('last_name');
$table->datetime('birth');
$table->string('town');
$table->string('country');
$table->string('image');
$table->timestamps();
});
}
//DirectorController
public function update(Request $request, Director $director)
{
$request->validate([
'first_name' => 'required',
'last_name' => 'required',
'birth' => 'required',
'town' => 'required',
'country' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'images/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
$director->update($input);
return redirect()->route('directors.index')->with('success', 'Director updated successfully.');
}
//DirectorModel
protected $fillable = [
'first_name',
'last_name',
'birth',
'town',
'country',
'image'];
public function movies() {
return $this->hasMany(Movie::class);
}
// edit.blade.php
#extends('directors.layout')
#section('content')
<div class="row">
<div class="col-lg-12 d-flex justify-content-between mt-5 mb-4">
<div class="pull-left">
<h2>Edit Director</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('directors.index') }}"><i class="fa-solid fa-delete-left"></i> Back</a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<div class="first d-flex justify-content-between">
<strong>Whoops!</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
There were some problems with your input. <br><br>
<ul>
#foreach ( $errors->all() as $error )
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('directors.update', $director->id) }}" method="POST">
#csrf
#method('PUT')
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>First Name:</strong>
<input type="text" name="first_name" value="{{ $director->first_name }}" class="form-control" placeholder="First Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Last Name:</strong>
<input type="text" name="last_name" value="{{ $director->last_name }}" class="form-control" placeholder="Last Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Birth:</strong>
<input type="text" name="birth" value="{{ $director->birth }}" class="form-control" placeholder="Birth">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Town:</strong>
<input type="text" name="town" value="{{ $director->town }}" class="form-control" placeholder="Town">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Country:</strong>
<input type="text" name="country" value="{{ $director->country }}" class="form-control" placeholder="Country">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Image:</strong>
<input type="file" name="image" class="form-control" placeholder="image">
<img src="/images/{{ $director->image }}" width="300px">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md12 text-center">
<button type="submit" class="btn btn-primary"><i class="fa-solid fa-square-plus"></i> Submit</button>
</div>
</div>
</form>
#endsection
You need to change your form as:
<form action="{{ route('directors.update', $director->id) }}" method="POST" enctype="multipart/form-data">

Mistake in validation in Laravel

Something is wrong with my validation. Data from the form is created and I can see it when I use the dd() function. But when it comes to creating and sending that data to the database it creates an empty row. My Laravel version is 8.83.17. Here's my route:
Route::middleware(['auth.amicms'])->name('amicms.')->prefix('amicms')->group(function() {
Route::resource('/posts', PostController::class);
});
Here's the request:
public function rules()
{
return [
'name_en' => 'required',
'body_en' => 'required',
'name_ua' => 'required',
'body_ua' => 'required',
'name_ru' => 'required',
'body_ru' => 'required',
'meta_title_en' => 'string',
'meta_description_en' => 'string',
'meta_keywords_en' => 'string',
'meta_title_ua' => 'string',
'meta_description_ua' => 'string',
'meta_keywords_ua' => 'string',
'meta_title_ru' => 'string',
'meta_description_ru' => 'string',
'meta_keywords_ru' => 'string',
'image' => 'required|image',
'price' => 'required',
'status' => 'required'
];
}
Here's the model:
protected $fillable = ['name_en, body_en, name_ua, body_ua, name_ru, body_ru,
meta_title_en, meta_description_en, meta_keywords_en, meta_title_ua, meta_description_ua, meta_keywords_ua,
meta_title_ru, meta_description_ru, meta_keywords_ru, image, price, status'];
Here's the controller
public function store(StorePostRequest $request)
{
$input = $request->all();
if ($image = $request->file('image')) {
$imageDestinationPath = 'uploads/';
$postImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($imageDestinationPath, $postImage);
$input['image'] = "$postImage";
}
Post::create($input);
return view ('amicms.posts.index', ['layout' => $this->layout]);
}
Here's the view:
form action="{{ route('amicms.posts.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Языковая версия</label>
<select id="language" class="custom-select"
name="language" required>
<option value="ru">Русский</option>
<option value="ua">Украинский</option>
<option value="en">English</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Статус</label>
<select class="custom-select #if($errors->has('status')) noty_type_error #endif"
name="status" id="" required>
<option value="1">Published</option>
<option value="0">Not Published</option>
</select>
</div>
</div>
</div>
#php($formLang = ['ru', 'ua', 'en'])
#for($i=0; $i<3;$i++)
<div id="build-form-{{ $formLang[$i] }}" class="d-none">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Name (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="name_{{ $formLang[$i] }}" type="text" placeholder=""
class="form-control #if($errors->has('name_ru')) noty_type_error #endif">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Full description of the entry (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<textarea class="form-control #if($errors->has('body')) noty_type_error #endif"
name="body_{{ $formLang[$i] }}" id="summernote"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Meta Title (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="meta_title_{{ $formLang[$i] }}" type="text" placeholder="" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Meta Keywords (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="meta_keywords_{{ $formLang[$i] }}" type="text" placeholder="" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Meta Description (<span class="text-uppercase">{{ $formLang[$i] }}</span>)</label>
<input name="meta_description_{{ $formLang[$i] }}" type="text" placeholder="" class="form-control">
</div>
</div>
</div>
</div>
#endfor
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Photo</label>
<input name="image" type="file" placeholder="" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Price</label>
<input name="price" type="number" placeholder="" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="text-right mrg-top-5">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</form>
Here's the migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name_en')->nullable();
$table->text('body_en')->nullable();
$table->string('name_ru')->nullable();
$table->text('body_ru')->nullable();
$table->string('name_ua')->nullable();
$table->text('body_ua')->nullable();
$table->text('meta_title_en')->nullable();
$table->text('meta_description_en')->nullable();
$table->text('meta_keywords_en')->nullable();
$table->text('meta_title_ru')->nullable();
$table->text('meta_description_ru')->nullable();
$table->text('meta_keywords_ru')->nullable();
$table->text('meta_title_ua')->nullable();
$table->text('meta_description_ua')->nullable();
$table->text('meta_keywords_ua')->nullable();
$table->string('image');
$table->decimal('price', 10, 2);
$table->integer('status');
$table->timestamps();
});
}
protected $fillable = [
'name_en','body_en','name_ua','body_ua','name_ru',' body_ru','meta_title_en','meta_description_en','meta_keywords_en','meta_title_ua','meta_description_ua','meta_keywords_ua','meta_title_ru','meta_description_ru','meta_keywords_ru','image','price','status'
];

dropdown list not shown in laravel

I've got problem with dropdown list.
i want to show a primary key as a dropdown list in view blade , but i can not make the right rout to show it. Have you any ideas how to solve this problem?
this my root
$objects = ['users', 'permissions', 'roles', 'coins','pillars','subtindicators'];
foreach ($objects as $object) {
Route::get("$object", ucfirst(str_singular($object))."Controller#index")->middleware("permission:browse $object")->name("{$object}");
Route::get("$object/datatable", ucfirst(str_singular($object))."Controller#datatable")->middleware("permission:browse $object")->name("{$object}.datatable");
Route::get("$object/add", ucfirst(str_singular($object))."Controller#add")->middleware("permission:add $object")->name("{$object}.add");
Route::post("$object/create", ucfirst(str_singular($object))."Controller#create")->middleware("permission:add $object")->name("{$object}.create");
Route::get("$object/{id}/edit", ucfirst(str_singular($object))."Controller#edit")->middleware("permission:edit $object")->name("{$object}.edit");
Route::post("$object/{id}/update", ucfirst(str_singular($object))."Controller#update")->middleware("permission:edit $object")->name("{$object}.update");
Route::get("$object/{id}/delete", ucfirst(str_singular($object))."Controller#delete")->middleware("permission:delete $object")->name("{$object}.delete");
Route::get("$object/{id}", ucfirst(str_singular($object))."Controller#view")->middleware("permission:view $object")->name("{$object}.view");
Route::get("$object/create", ucfirst(str_singular($object))."Controller#list")->middleware("permission:add $object")->name("{$object}.create");
this my controller
public function add()
{ $strs = DB::table('stargets')->select('*')->get();;
return view('subtindicators.add-edit',compact('strs'));
}
public function update(Request $request, $id)
{
$object = $this->objectModel::find($id);
$object->update([
'skey_name' => $request->skey_name,
'Subtarget_base' => $request->Subtarget_base,
'Subtarget_end' => $request->Subtarget_end,
'subtarget_id' => $request->subtarget_id
]);
if ($request->save == 'browse')
return redirect()->route("{$this->objectName}");
elseif ($request->save == 'edit')
return redirect()->route("{$this->objectName}.edit", ['id' => $object]);
elseif ($request->save == 'add')
return redirect()->route("{$this->objectName}.add");
else
return redirect($request->previous_url);
}
this my blade
#extends('adminlte::page')
#include('bread.title')
#section('main-content')
<div class="container-fluid spark-screen">
<div class="row">
{!! csrf_field() !!}
<form class="form-horizontal" action="{{$actionName=='edit'?route("{$objectName}.update",['id'=>$object->id]):route("{$objectName}.create") }}" method="post">
{!! csrf_field() !!}
<input type="hidden" name="previous_url" value="{{ url()->previous() }}">
<form class="form-horizontal" action="{{ $actionName == 'edit' ? route("{$objectName}.update", ['id' => $object->id]) : route("{$objectName}.create") }}" method="post">
{!! csrf_field() !!}
<input type="hidden" name="previous_url" value="{{ url()->previous() }}">
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">{{ ucfirst($actionName) }} {{ ucfirst($objectName) }} {{ !empty($object) ? "(ID $object->id)" : '' }}</h3>
<div class="box box-solid">
<div class="box-header with-border">
<h3 class="box-title">{{ ucfirst($actionName) }} {{ ucfirst($objectName) }} {{ !empty($object) ? "(ID $object->id)" : '' }}</h3>
<div class="box-tools pull-right">
<button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
</div>
</div>
</div>
<div class="box-body">
<div class="form-group">
<label for="" class="col-md-2 control-label">col</label>
<div class="col-md-10">
<input type="text" name="skey_name" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_arname : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-2 control-label">cl_d</label>
<div class="col-md-10">
<input type="text" name="Subtarget_base" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_enname : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-md-2 control-label">cl_e</label>
<div class="col-md-10">
<input type="text" name="Subtarget_end" class="form-control" maxlength="255" value="{{ !empty($object) ? $object->coin_arsymbol : '' }}" required>
</div>
</div>
<div class="form-group">
<label for="" class="form-control">c_i</label>
<div class="col-md-10">
<select class="form-control" name="starget_id">
<option selected disabled value = " ">choos</option>
#foreach($strs as $vis)
<option value="{{$vis->id}}">{{$vis->target_name}}</option>
#endforeach
<!-- <p class="form-control-static">{{ $object->subtarget_id }}</p>-->
</div>
</div>
<div class="form-group has-feedback">
<label for="title">main<span class="text-danger">*</span></label>
<select class="form-control" name="starget_id">
<option selected disabled value = " ">choos</option>
#foreach($strs as $slider2)
<option value="{{$slider2->id}}" {{ $slider2->id== $slider->starget_id ? 'selected' : '' }}>{{$slider2->vname}}</option>
#endforeach
</div>
</div>
</div>
<div class="box-footer">
#include('bread.add-edit-actions')
</div>
</div>
</form> </form>
</div>
</div>
</div>
#endsection
this error what i got
ErrorException (E_ERROR)
Undefined variable: actionName (View: C:\project Last\resources\views\bread\title.blade.php) (View: C:\Ministry Last\resources\views\bread\title.blade.php)
You should forward $actionName variable to your view:
public function add()
{
$strs = DB::table('stargets')->select('*')->get();
$actionName = 'edit';
return view('subtindicators.add-edit',compact('strs', 'actionName'));
}
However this will hardcode the form to being an "edit" form. You must see what you really want with your logic.

"Trying to get property 'name' of non-object

I had a Laravel script installed
Now I want to go to the services list page, but with the "Trying to get the property 'name' of non-object" encountered.
please help me
My error:
Trying to get property 'name' of non-object (View: /mylocalhost/core/resources/views/admin/service.blade.php)
in line 36:
category->name); ?>
service.blade.php code:
#section('page_name', 'Services')
<a class="btn btn-outline-success btn-lg" href="#" data-toggle="modal" data-target="#addService"><i
class="fa fa-plus-circle"></i> Add Service</a>
#endsection
#section('body')
<ul class="orders-ul">
<li class="text-color"><a class="btn btn-outline-secondary" href="{{ route('api.service') }}" target="_blank">API Services List</a></li>
</ul>
<div class="row">
#include('admin.layouts.flash')
<div class="col-md-12">
<div class="tile">
<h3 class="tile-title">Services</h3>
<table class="table table-hover">
<thead>
<tr>
<th>Serial</th>
<th>Name</th>
<th>Category</th>
<th>Price per 1K</th>
<th>Min</th>
<th>Max</th>
<th>Order Response</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($items as $key => $item)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $item->name }}</td>
<td>{{ $item->category->name }}</td>
<td>{{ $item->price_per_k }}</td>
<td>{{ $item->min }}</td>
<td>{{ $item->max }}</td>
<td>{{ $item->service_id == 0? 'Manual' : 'API' }}</td>
<td>
{!! $item->status == 0 ? '<b style="color:#d35400">Inactive</b>' : '<b style="color:#16a085">Active</b>' !!}
</td>
<td>
<button class="btn btn-outline-info service_edit_btn"
data-toggle="modal"
data-target="#editService"
data-route="{{ route('service.update', $item->id) }}"
data-category="{{ $item->category_id }}"
data-name="{{ $item->name }}"
data-price="{{ $item->price_per_k }}"
data-min="{{ $item->min }}"
data-max="{{ $item->max }}"
data-service_id="{{ $item->service_id }}"
data-details="{{ $item->details }}"
data-status="{{ $item->status }}">
<i class="fa fa-edit`enter code here`"></i></button>
<button class="btn btn-outline-danger service_dlt_btn"
data-toggle="modal"
data-target="#delService"
data-route="{{ route('service.delete', $item->id) }}">
<i class="fa fa-trash"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<div class="modal fade" id="addService" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4><b>Add Service</b></h4>
</div>
<div class="modal-body">
<div class="portlet light bordered">
<div class="portlet-body form">
<form role="form" action="{{ route('service.store') }}" method="post">
#csrf
<div class="form-body">
<div class="form-group">
<label for=""><b>Category</b></label>
<select name="category_id" class="form-control form-control-lg">
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for=""><b>Name</b></label>
<input type="text" name="name" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Price per 1k</b></label>
<div class="input-group">
<input type="text" name="price_per_k" class="form-control form-control-lg">
<div class="input-group-append">
<span class="input-group-text">{{ $general->currency_symbol }}</span>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for=""><b>Min</b></label>
<input type="text" name="min" class="form-control form-control-lg">
</div>
<div class="form-group col-md-6">
<label for=""><b>Max</b></label>
<input type="text" name="max" class="form-control form-control-lg">
</div>
</div>
<div class="form-group">
<label for=""><b>Details</b></label>
<textarea class="form-control" name="details" rows="8"></textarea>
</div>
<div class="form-group">
<label for=""><b>service Id (If order process through API)</b></label>
<input type="text" name="service_id" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Status</b></label>
<input data-toggle="toggle" data-onstyle="success" data-offstyle="danger"
data-on="Active" data-off="Inactive" data-width="100%" type="checkbox" name="status" value="1">
</div>
</div>
<div class="tile-footer">
<button class="btn btn-primary btn-block btn-lg" type="submit"><i
class="fa fa-fw fa-lg fa-check-circle"></i>Save
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<div class="modal fade" id="editService" tabindex="-1" role="basic" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4><b>Edit Service</b></h4>
</div>
<div class="modal-body">
<div class="portlet light bordered">
<div class="portlet-body form">
<form role="form" action="" method="post"
id="serviceEditdForm">
#csrf
#method('put')
<div class="form-body">
<div class="form-group">
<label for=""><b>Category</b></label>
<select name="category_id" id="category_id" class="form-control form-control-lg">
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for=""><b>Name</b></label>
<input type="text" name="name" id="name" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Price per 1k</b></label>
<div class="input-group">
<input type="text" name="price_per_k" id="price_per_k" class="form-control form-control-lg">
<div class="input-group-append">
<span class="input-group-text">{{ $general->currency_symbol }}</span>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<label for=""><b>Min</b></label>
<input type="text" name="min" id="min" class="form-control form-control-lg">
</div>
<div class="form-group col-md-6">
<label for=""><b>Max</b></label>
<input type="text" name="max" id="max" class="form-control form-control-lg">
</div>
</div>
<div class="form-group">
<label for=""><b>Details</b></label>
<textarea class="form-control" name="details" id="details" rows="8"></textarea>
</div>
<div class="form-group">
<label for=""><b>service Id (If order process through API)</b></label>
<input type="text" name="service_id" id="service_id" class="form-control form-control-lg">
</div>
<div class="form-group">
<label for=""><b>Status</b></label>
<input data-toggle="toggle" data-onstyle="success" data-offstyle="danger"
data-on="Active" data-off="Inactive" data-width="100%" type="checkbox" name="status" id="status" value="1">
</div>
</div>
<div class="tile-footer">
<button class="btn btn-primary btn-block btn-lg" type="submit"><i
class="fa fa-fw fa-lg fa-check-circle"></i>Save
</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<div class="modal fade" id="delService">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-body">
<form action="" method="post" id="serviceDelForm">
#csrf
#method('delete')
<h3 class="d-flex justify-content-center">Are you want to delete this Service?</h3>
<div class="tile-footer d-flex justify-content-center">
<button class="btn btn-primary" type="submit"><i class="fa fa-fw fa-lg fa-check-circle"></i>Confirm
</button>
<a class="btn btn-danger" href="#" data-dismiss="modal"><i
class="fa fa-fw fa-lg fa-times-circle"></i>Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.service_edit_btn', function () {
var route = $(this).data('route');
var category = $(this).data('category');
var name = $(this).data('name');
var price = $(this).data('price');
var min = $(this).data('min');
var max = $(this).data('max');
var service_id = $(this).data('service_id');
var details = $(this).data('details');
var status = $(this).data('status');
$('#category_id').val(category).attr('selected', 'selected');
$('#name').val(name);
$('#price_per_k').val(price);
$('#min').val(min);
$('#max').val(max);
$('#service_id').val(service_id);
$('#details').val(details);
$('#serviceEditdForm').attr('action',route);
if(status == 1){
$('#status').bootstrapToggle('on');
}else{
$('#status').bootstrapToggle('off');
}
});
$(document).on('click', '.service_dlt_btn', function () {
var route = $(this).data('route');
$('#serviceDelForm').attr('action', route);
});
});
</script>
#endsection
And service list controller in Admin controller:
public function service(){
$categories = Category::orderBy('name')->get();
$items = Service::orderBy('category_id')->paginate(10);
return view('admin.service', compact('items', 'categories'));
}
public function serviceStore(Request $request){
$this->validate($request, [
'category_id' => 'required',
'name' => 'required|unique:services,name',
'price_per_k' => 'required',
'min' => 'required',
'max' => 'required',
'details' => 'required',
], [
'category_id.required' => 'Category name is required',
'price_per_k.required' => 'price per 1k is required',
]);
$excp = $request->except('_token', 'status', 'service_id');
$status = $request->status == 1? 1:0;
if(isset($request->service_id)){
$service_id = $request->service_id;
}else{
$service_id = 0;
}
$sev = Service::create($excp + ['status' => $status, 'service_id' => $service_id]);
$users = User::all();
foreach ($users as $user){
$servicePrice = new ServicePrice();
$servicePrice->category_id = $sev->category_id;
$servicePrice->service_id = $sev->id;
$servicePrice->user_id = $user->id;
$servicePrice->price = $sev->price_per_k;
$servicePrice->save();
}
session()->flash('success', 'Service Stored successfully');
return back();
}
public function serviceUpdate(Request $request, $id){
$this->validate($request, [
'category_id' => 'required',
'name' => 'required',
'price_per_k' => 'required',
'min' => 'required',
'max' => 'required',
'details' => 'required',
], [
'category_id.required' => 'Category name is required',
'price_per_k.required' => 'price per 1k is required',
]);
$excp = $request->except('_token', 'status', 'service_id');
$status = $request->status == 1? 1:0;
if(isset($request->service_id)){
$service_id = $request->service_id;
}else{
$service_id = 0;
}
Service::findOrFail($id)->update($excp + ['status' => $status, 'service_id' => $service_id]);
session()->flash('success', 'Service Updated successfully');
return back();
}
public function serviceDelete($id){
Service::findOrFail($id)->delete();
session()->flash('success', 'Service deleted successfully');
return back();
}
This means your item don't have category, So you can do something like this.
<td>
#if(!empty($item->category)) {{ $item->category->name }} #endif
</td>
Other way to solve this problem using php7 is to use null coalescing operator which:
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
<td>{{ $item->category->name ?? '' }}</td>

Show part of page body to paid users in laravel

I've store in my application (LARAVEL 5.4) and I want to share some download links in bottom of my product body but to hide it from everyone except who paid for that specific product.
Here is explanation of how I get user data and their request for specific product:
Form of their request:
<form class="form-horizontal" action="{{route('buy_course')}}" method="POST" id="contact_form">
{{ csrf_field() }}
<input name="user_id" value="{{ Auth::user()->id }}" class="form-control" type="hidden">
<input name="course_id" value="{{ $course->id }}" class="form-control" type="hidden">
<div class="form-group">
<label class="col-md-3 control-label">UserName</label>
<div class="col-md-9 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user"></i></span>
<input name="username" value="{{ Auth::user()->username }}" class="form-control" type="text" readonly>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-3 control-label">E-Mail</label>
<div class="col-md-9 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
<input name="email" value="{{ Auth::user()->email }}" class="form-control" type="text" readonly>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Course</label>
<div class="col-md-9 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-graduation-cap"></i></span>
<input name="course" value="{{ $course->course_name }}" class="form-control" type="text" readonly>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="type">Type</label>
<div class="col-md-9 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-file-code-o"></i></span>
<select class="form-control" id="type" name="type">
<option value="">Select Type</option>
<option value="Download Link">Download Link</option>
<option value="Physical Disk">Physical Disk</option>
</select>
</div>
</div>
</div>
#if (!empty($course->extra_description))
<div class="form-group">
<label class="col-md-3 control-label" for="type">{{ $course->extra_title }}</label>
<div class="col-md-9 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-file-code-o"></i></span>
<select class="form-control" id="type" name="extra_price">
<option value="">Do you need extra?</option>
<option value="{{$course->extra_price}}">Yes - Add {{$course->extra_price}} Rp</option>
<option value="0">No</option>
</select>
</div>
</div>
</div>
#endif
<div class="form-group">
<label class="col-md-3 control-label">Note to seller</label>
<div class="col-md-9 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-comment-o"></i></span>
<textarea name="note" id="text" placeholder="Your note to seller here..." class="form-control" rows="8" ></textarea>
</div>
<h6 class="pull-right" id="count_message"></h6>
</div>
</div>
<div class="text-center">
<input type="submit" class="btn btn-block btn-success" value="Send">
</div>
</form>
The controller:
public function postbuycourse(Request $request) {
$this->validate($request, array(
'user_id' => 'required',
'username' => 'required',
'email' => 'required|email',
'course' => 'required',
'note' => 'sometimes|max:500',
'type' => 'required',
));
DB::table('purchases')->insert([
'user_id' => $request->user_id,
'course_id' => $request->course_id,
'note' => $request->note,
'type' => $request->type,
'status' => 0,
'invoice_nu' => str_random(15),
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
]);
$data = array(
'username' => $request->username,
'email' => $request->email,
'course' => $request->course,
'note' => $request->note,
'type' => $request->type,
);
Mail::send('emails.buycourse', $data, function($message) use ($data) {
$message->from($data['email']);
$message->to('xxxxxx#xxxxxx.com');
$message->subject($data['course']);
});
$id = $request->course_id;
$course = Course::findOrFail($id);
Mail::to($request->user())->send(new CourseReceived($course));
Session::flash('flash_message', 'Your Order was sent. Our sell team will contact you shortly.');
return redirect()->back();
}
And here is how I show them their order and their order status that if is paid or not:
#if (Auth::user()->purchase->count() )
<h4><i class="fa fa-graduation-cap"></i> Courses Orders</h4>
<table class="mt-20 table table-bordered table-hover table-responsive">
<thead>
<tr class="bg-primary">
<th class="text-center">ID</th>
<th class="text-center">Invoice Number</th>
<th class="text-center">Course Name</th>
<th class="text-center">Note</th>
<th class="text-center">Sum</th>
<th class="text-center">Status</th>
<th class="text-center">Time</th>
<th class="text-center">Expire</th>
<th class="text-center">Options</th>
</tr>
</thead>
<tbody class="text-center">
#foreach ($purchases as $purchase)
<tr>
<td id="primary">{{$purchase->id}}</td>
<td>{{$purchase->invoice_nu}}</td>
<td>{{$purchase->course->course_name}}</td>
<td>
#if(!empty($purchase->note))
{{ $purchase->note }}
#else
-
#endif
</td>
<td>
#if( ! empty($purchase->course->course_disscount))
<span class="text-primary">Price: <del>{{$purchase->course->course_price}}</del></span><br>
<span class="text-danger">disscount: {{$purchase->course->course_disscount}}</span>
<hr>
<span class="text-success">Total: {{ number_format($purchase->course->course_price - $purchase->course->course_disscount, 0) }} Rp</span>
#else
{{ number_format($purchase->course->course_price, 0) }} Rp
#endif
</td>
<td>
#if($purchase->status == 0)
<span class="text-danger">Waiting Payment</span>
#else
<span class="text-success">Paid</span>
#endif
</td>
<td>{{ $purchase->created_at->format('d, M, Y | h:i A') }}</td>
<td>
#if($purchase->status == 0)
<span class="text-danger">-</span>
#else
<span class="text-success">{{ $purchase->created_at->format('d, M, Y | h:i A') }}</span>
#endif
</td>
<td>
Payment
<i class="fa fa-pencil"></i> Edit
{!! Form::open(['method' => 'DELETE', 'route' => ['userscourses.destroy', $purchase->id] ]) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-sm btn-danger btn-block mt-20']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</tbody>
</table>
Thanks.
You can use laravel Gate and policies features for achieving that, You can read the documentation once.

Categories