Update photo using Laravel - php

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">

Related

302 found in Laravel project

Route
Route::get('/addproduct', [UserController::class, 'addproduct'])->name('addproduct');
Route::post('/addnewproduct', [UserController::class, 'addnewproduct'])->name('addnewproduct');
Route::get('/showproducts', [UserController::class, 'showproducts'])->name('showproducts');
Controller
public function addproduct()
{
return view('addProduct');
}
public function addnewproduct(Request $request)
{
$user_id = Auth::user()->id;
$request->validate([
'file' => 'required|mimes:jpg,png,gif,svg',
'name' => 'required|string|min:3|max:30',
'description' => 'required|string|min:1|max:255',
'category' => 'required|string|max:255',
]);
$productModel = new Product();
$filename =time().'_' .$request->name;
$filePath = $request->file('file')->move('upload', $filename);
$productModel->name = $request->name;
$productModel->description = $request->description;
$productModel->category = $request->category;
$productModel->image = $filePath;
$productModel->save();
return redirect()->route('showproducts');
}
public function showproducts()
{
$user_id = Auth::user()->id;
$results=DB::select('SELECT * FROM products');
$data = [
'results' =>$results
];
return view('showProduct')->with($data);
}
View
<div class="card-body">
<form method="POST" action="{{ route('addnewproduct') }}" class="needs-validation form" enctype="multipart/form-data" novalidate>
#csrf
<div class="row">
<div class="col-sm-6">
<input type="file" id="input-file-now" class="form-control dropify" name="file" required/>
</div>
<div class="col-sm-6">
<div class="row mb-3">
<label for="validationName" class="form-label">Product name</label>
<div class="input-group has-validation">
<input type="text" class="form-control" name="name" id="validationName" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
You have to enter Product name!
</div>
</div>
</div>
<div class="row mb-3">
<label for="validationCategory" class="form-label">Category</label>
<div class="input-group has-validation">
<select class="form-select" name="category" id="validationCategory" required>
<option selected disabled value="">Select...</option>
<option value="c1">c1</option>
<option value="c2">c2</option>
</select>
</div>
<div class="invalid-feedback">
Please select Category
</div>
</div>
<div class="row mb-3">
<label for="validationDes" class="form-label">Description</label>
<div class="input-group has-validation">
<textarea type="text" class="form-control text-des" name="address" id="validationDes" aria-describedby="inputGroupPrepend" required></textarea>
<div class="invalid-feedback">
Please enter product descriiption in here.
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
<label class="form-check-label" for="invalidCheck">
Check it.
</label>
<div class="invalid-feedback">
You have to checkbox!
</div>
</div>
</div>
<div class="row">
<div class="float-end">
<button class="btn btn-primary sumbtn float-end" type="submit"><i class="bi bi-person-plus-fill"></i> ADD</button>
</div>
</div>
</form>
</div>
after enter all fields and file select and then click checkbox, but when I click button don't go to showproducts page, and don't save enterd data and file.
view screenshot
after click button get 302 and not redirect to "showproducts"
Please help me, I'm very very stress with that problem

Laravel 8 CRUD Edit page cannot display correctly

I am currently making laravel project using internet references and now I'm stuck at CRUD operation.
I use Laravel 8 with jetstream for auth, now ui template assets, bootstrap.
I tried several CRUD codes from different sources and everything worked except for edit page.
Index page:
Edit page:
This is my route:
Route::resource('projects', ProjectController::class);
My controller:
public function edit(Project $project)
{
return view('projects.edit', compact('project'));
}
public function update(Request $request, Project $project)
{
$request->validate([
'name' => 'required',
'introduction' => 'required',
'location' => 'required',
'cost' => 'required'
]);
$project->update($request->all());
return redirect()->route('projects.index')
->with('success', 'Project updated successfully');
}
The blade file:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Edit Product</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('projects.index') }}" title="Go back"> <i class="fas fa-backward "></i> </a>
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> 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('projects.update', $project->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>Name:</strong>
<input type="text" name="name" value="{{ $project->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Introduction:</strong>
<textarea class="form-control" style="height:50px" name="introduction"
placeholder="Introduction">{{ $project->introduction }}</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Location:</strong>
<input type="text" name="location" class="form-control" placeholder="{{ $project->location }}"
value="{{ $project->location }}">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Cost:</strong>
<input type="number" name="cost" class="form-control" placeholder="{{ $project->cost }}"
value="{{ $project->location }}">
</div>
</div>
<div class="text-center col-xs-12 col-sm-12 col-md-12">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
#endsection
I tried changing the edit blade file codes to different ones but still same. I tried different method from online for the edit function in controller but nothing change. I also tried completely different coding, different model controllers and all, still the same. Only edit page turns out that way. Anyone have any clue?

Laravel 8 safe (think problem datetime-local input field to mysql)

When I click save on my form, the page reloads. Which is correct until then. Unfortunately, it does not save the data for me in the database. So I tried to find the error with dd($request->all()). Unfortunately, I haven't found a real error as far as the correct data is loaded on the form. However, they never end up in the database. I currently only have one guess that it is due to the wrong format of DateTime_local input. But can't say for sure.
I don't get any error messages or anything like that.
Here is a small snippet of my code:
app/Http/Controllers/TasksController
public function store(Request $request)
{
// validate all required Data
$request->validate([
'title' => 'required',
'user' => 'required',
'labels' => 'required',
'work' => 'required',
'start_work' => 'required',
'problems' => 'required',
'stop_work' => 'required',
]);
$input = $request->all();
Task::create($input);
return back()->with('success', 'Successfully saved.');
}
app/Models/Task.php
class Task extends Model
{
use HasFactory;
public $fillable = ['title', 'user', 'labels', 'work', 'start_work', 'problems', 'stop_work'];
}
Migration
public function up()
{
Schema::create('task', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('user');
$table->string('label');
$table->string('work');
$table->string('problems');
$table->dateTime('start_work');
$table->dateTime('stop_work');
$table->timestamps();
});
}
View snippet
#extends('layouts.app')
#section('content')
<!-- Success message -->
#if(Session::has('success'))
<div class="alert alert-success">
{{Session::get('success')}}
</div>
#endif
<form method="post" action="{{ route('screate') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<section class="person">
<div class="container-fluid">
<div class="card card-default">
<div class="card-header">
<h3 class="card-title">Daten</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="title">title</label>
<input type="text" class="form-control {{ $errors->has('title') ? 'error' : '' }}" id="title" name="title" required>
</div>
<!-- /.form-group -->
</div>
<div class="col-md-4">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control {{ $errors->has('username') ? 'error' : '' }}" id="username" name="username">
</div>
</div>
<!-- /.form-group -->
<div class="col-md-4">
<div class="form-group">
<label for="labels">Labels</label>
<select id="labels" name="label" class="select2 select2-hidden-accessible {{ $errors->has('label') ? 'error' : '' }}" multiple="" name="label[]" style="width: 100%;" data-select2-id="5" tabindex="-1" aria-hidden="true">
#foreach($labels as $label)
<option value="{{ $label->id }}">{{ $label->name }}</option>
#endforeach
</select>
</div>
</div>
<!-- /.form-group -->
<div class="col-md-4">
<div class="form-group">
<label for="work">work</label>
<input type="text" class="form-control {{ $errors->has('work') ? 'error' : '' }}" id="work" name="work">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="start_work">Start-Work</label>
<input type="datetime-local" class="form-control {{ $errors->has('start_work') ? 'error' : '' }}" id="start_work" name="start_work">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="problems">Problems</label>
<input type="text" class="form-control {{ $errors->has('problems') ? 'error' : '' }}" id="problems" name="problems">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="stop_work">Stop-Work</label>
<input type="datetime-local" class="form-control {{ $errors->has('start_work') ? 'error' : '' }}" id="stop_work" name="stop_work">
</div>
</div>
</div>
<!-- /.row -->
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div><!-- /.container-fluid -->
</section>
<section class="options">
<div class="row">
<div class="col-md-2 centered">
<button class="btn btn-danger" href="{{ route('home') }}">
<i class="fas fa-times">
</i>
Abbrechen
</button>
</div>
<div class="col-md-2">
<button class="btn btn-success" type="submit" name="submit">
<i class="fas fa-plus">
</i>
Speichern
</button>
</div>
</div>
</section>
</form>
#endsection
I hope you can help me with this small problem.
edit:
Here is my dd output:
dd() output

Route [student.update] not defined. using laravel 7

i am a beginner of laravel. i ran into the problem with Route [student.update] not defined. using laravel 7. when run the laravel project. what i tried so far i attached below.
i attached the controller and view and route file below i don't what was a problem.
Controller
public function edit(Student $student)
{
return view('edit')->with('student',$student);
}
public function update(Request $request, Student $student)
{
Student::update([
'name' => $request->name,
'phone' => $request->phone,
'address' => $request->address,
'created_at' => now(),
]);
return redirect()->route('student.index')->with('success', 'Student has been Updatedddd');
}
edit.blade.php
<form action="{{ route('student.update',$student->id) }}" method="POST">
#csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $student->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Phone:</strong>
<input class="form-control" name="phone" value="{{ $student->phone }}" placeholder="Phone"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Address:</strong>
<input class="form-control" name="address" value="{{ $student->address }}" placeholder="Address"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
index.blade.php
#extends('layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 7 CRUD Example from scratch - ItSolutionStuff.com</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('student.create')}}"> Create New Student</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Phone</th>
<th>Address</th>
<th width="280px">Action</th>
</tr>
#foreach ($students as $student)
<tr>
<td>{{ $student->id }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->phone }}</td>
<td>{{ $student->address }}</td>
<td>
<a class="btn btn-primary" href="{{ route('student.edit',$student->id) }}">Edit</a>
<button type="submit" class="btn btn-danger">Delete</button>
</td>
</tr>
#endforeach
</table>
{!! $students->links() !!}
#endsection
Routes
Route::get('/students/{student}', 'StudentController#edit')->name('student.edit');
Route::get('/students/{student}', 'StudentController#update')->name('student.update');
Your update route is defined as a get route while your edit form is trying to submit a post request to the route
You should ideally have the update route defined as a PUT or PATCH route. And if you are using Laravel 8.x, then you should have FQCN for the controllers
//import use statements at the top
//use Illuminate\Support\Facades\Route;
//use App\Http\Controllers\StudentController;
Route::match(['PUT', 'PATCH'], '/students/{student}', [StudentController::class, 'update'])->name('student.update');
And then make a PUT or PATCH submit request from edit.blade.php
<form action="{{ route('student.update',$student->id) }}" method="POST">
#csrf
#method('PUT') //Method spoofing
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" value="{{ $student->name }}" class="form-control" placeholder="Name">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Phone:</strong>
<input class="form-control" name="phone" value="{{ $student->phone }}" placeholder="Phone"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Address:</strong>
<input class="form-control" name="address" value="{{ $student->address }}" placeholder="Address"></textarea>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
And change the controller method
public function update(Request $request, Student $student)
{
$student->update([
'name' => $request->name,
'phone' => $request->phone,
'address' => $request->address,
'created_at' => now(),
]);
return redirect()->route('student.index')->with('success', 'Student has been Updatedddd');
}

Send attachment in laravel

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(),
]);
}
}

Categories