First of all, I want to save comments after editing.I'm able to save the other features, but now I need to save comments too because they are in other table.
Here is my code for comments:
#foreach($event_comm as $comm)
<div class="row">
<div class="col-md-4">
<label class="label" style="color: black">Comment by {{$comm->user->username}}</label>
<label class="input">
{{ Form::text('comments', $comm->comments) }}
</label>
#endforeach
My update function
public function update($type, $id)
{
/* print_r(Input::all()); die; */
if($type == "Opinion")
{
$article = \App\Opinion::find($id);
$article->subject = Request::input('subject');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->opinion = Request::input('opinion');
$article->update();
}
if($type == "Event")
{
$event_comm = EventComment::where('event_id', $id)->get();
$article = \App\Event::find($id);
$article->subject = Request::input('subject');
$event_comm->comments = Request::input('comments');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->website = Request::input('website');
$article->email = Request::input('email');
$article->telephone = Request::input('telephone');
$article->information = Request::input('information');
$article->update();
}
return redirect(URL::previous())
->with(compact('event_comm'));
}
I've already tried to add $event_comm->comments = Request::input('comments'); but doesn't work.
2.Second problem.I want to also delete comments from database with a button or something like that.I found a route but I'm not sure if works.I need to know how to add this into my file?With a button ?
My route
Route::get('admin/article/deleteComment/{type}/{id}',['as' => 'deleteComment', 'uses' => 'ArticleController#deleteComment']);
public function deleteComment($type, $id)
{
if($type == "Event")
{
$comment = \App\EventComment::find($id);
}
if($type == "Opinion")
{
$comment = \App\OpinionComment::find($id);
}
$comment->delete();
return redirect('admin/comments');
}
Button:
<button href="{{ url('deleteComment',$type, $id) }}" role="button" class="btn btn-xs btn-danger" onclick="return confirm('Are you sure you want to delete this comment?');">Delete <i class="fa fa-trash"></i></button>
Related
I'm working on a form where you have to enter all information you need and at the end, on save all information will be saved at the same times. The form have a list of images where you can add, change and delete pictures.
The way it was made is that all inputs refer to the name carousels[]. Adding the file is alright, the problem is that this way I have no way to identify in backend which file I have to delete or change.
I'm wondering if any Laravel master know a better way to handle a list of files over a form the way a need it to work. So I would be able to add new images, replace an old image by a new one and/or delete a specific image.
There are the pieces of code I'm working with.
Frontend:
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="carrousels[]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Backend
public function update(UpdateRequest $request)
{
try {
$id = $request->id;
$carrouselFolder = config('constants.DEFAULT.UPLOAD_FOLDERS.CARROUSEL');
$carrousels = [];
Log::debug($request->carrousels);
if ($request->carrousels) {
foreach ($request->carrousels as $image) {
if (!empty($image)) {
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
}
return redirect()->to(route('...'))
->with('toastSuccess', '...');
} catch (\Exception $e) {
return redirect()->back()->with('toastError', $e->getMessage());
}
}
send another parameter with old carousel, retrive it in controller then if both not empty, delete the old image . you can try this
View code
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="text" name="oldcarrousels[{{$i}}]" value="{{ !empty($carrousel[$i]) ?$carrousel[$i] :'' }}">
<input type="file" name="carrousels[{{$i}}]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Controller code
foreach ($request->carrousels as $in=>$image) {
if (!empty($image)) {
if (!empty($request->oldcarrousels[$in]) || $request->oldcarrousels[$in]!='') {
//image deleting code here
}
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
I inserted the image in my database, now I am trying to edit the images and the edited image should be deleted from my folder and a new image should be updated there. Could you please help me where I am mistaking?
Here is my Controller.php file
public function edit($slider)
{
$property=Property::all();
$slider = Slider::find($slider);
$data = ['property'=>$property, 'slider'=>$slider];
return view('admin.slider.edit', $data);
}
public function update(Request $r, $id)
{
$slider=Slider::find($id);
if( $r->hasFile('slider_thumb')){
$thums = $r->slider_thumb;
$slider_thumb = uniqid($chr).'.'.$thums->getClientOriginalExtension();
$img = Image::make($thums->getRealPath());
$img->resize(204, 107, function ($constraint) {
$constraint->aspectRatio();
});
$thumbPath = public_path().'/slider_img/'.$slider_thumb;
if (file_exists($thumbPath)) {
$this->removeImage($thumbPath);
}
$img->save($thumbPath);
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($thumbPath);
$slider_thumbimg = $slider_thumb;
}else{
$slider_thumb = NULL;
}
$slider->property_id = $r->property_id;
$slider->slider_image=$slider_imageimg;
$slider->save();
return redirect('/admin/slider');
}
}
here is my HTML file
<form class="form-horizontal" method="POST" action="{{ route('slider.update',['id'=>$slider->id]) }}" enctype="multipart/form-data">
#csrf
#method('PUT')
#if($slider->slider_image == NULL or $slider->slider_image == '')
<img src="{{asset('images/no-image-found.jpg')}}" style="width: 100px; height: 100px;">
#else
<img src="{{ asset('slider_img/'.$slider->slider_image) }}" style="width: 100px; height: 80px;">
#endif
<input type="file" name="slider_image" value="{{ $slider->slider_image }}">
<div class="form-group">
<div class="col-sm-12 text-right">
<button type="submit" class="btn btn-info">
<i class="fa fa-check"></i> Save
</button>
</div>
</div>
</form>
You did not use Laravel standards. you need to refer to laravel filesystem document to upload file. then you need to check request file exist. if request has new file; you should remove old file and upload new file. in else you should not remove old file.
follow below code:
public function store(PostRequest $request,string $slug = null)
{
$postData = $request->all();
//upload and set thumbnail of post, if exist
if($request->file("thumbnail")){
$image = new Images();
$thumbnailName = $image->uploadFile($request,"thumbnail",config("upload_image_path.post-thumbnail"));
$postData["thumbnail"] = $thumbnailName;
}
$post = $this->postService->save($postData,$slug);
whene i do the login action it return the error above where there is no user all work good
$currentTime = date("Y-m-d");
if(Auth::check()){
$user = Auth::user();
$favorie = $user->favorie;
$favprds = $favorie->produits;
}else{
$favprds = [];
}
this is my blade i believe that there is no probleme with blade
#for ( $i = 0; $i < count($favprds) ;$i++)
#if ($favprds[$i]->id == $pro->id)
<div class="tinv-wishlist-clear">
<a style="color:red;" href="{{ url('deleteFavorie/'.$pro->id) }}"><i class="fa fa-heart"></i></a>
</div>
#break
#elseif($favprds[$i]->id != $pro->id && $i == count($favprds)-1)
<div class="tinv-wishlist-clear">
<i class="klbth-icon-heart-1"></i>
</div>
#endif
#endfor
#if(count($favprds) == 0)
<div class="tinv-wishlist-clear">
<a style="color:#7f8c8d" href="{{ url('add-to-favorie/'.$pro->id) }}"><i class="klbth-icon-heart-1"></i></a>
</div>
#endif
it seems that the way i access the products is the wrong way thought i still have to test if the there's a probleme with adding to the favorite product
$currentTime = date("Y-m-d");
if ($favorie = auth()->user()->favorie ?? false) {
$favprds = $favorie->produits;
} else {
$favprds = [];
}
M working on a solution where by i need to pass data from controller to view, Based on the id.
I've tested each variable one by one for see if there is actual data contained in those variables.
one-by-one produces all the values required and as soon as i comment out the var_dumps(). Throws an Undefined index error.
Please See code below:
View
<td>
<a href="view-campaign/{{$item->id}}" class="btn btn-success mb-2"
data-toggle="tooltip" title="view campaign">
<i class="fa fa-eye"></i>
</a>
</td>
Controller
public function viewCampaign($id){
//return var_dump($id);
$img = null;
//firebase configs and send to firebase
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/serviceKey.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri('https://projectName.firebaseio.com/')
->create();
$database = $firebase->getDatabase();
$ref = $database->getReference('CampaignCollection')->getValue();
foreach($ref as $key){
$item = $key['id'];
//return var_dump($item);
$poster = $key['Poster'];
//return var_dump($poster);
if($item = $id){
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
return view('view-campaign')->with('img',$img);
}
Route
Route::get('view-campaign/{id}','CampaignController#viewCampaign');
View::Results
#extends('layouts.layout')
#section('content')
<div class="col-md-12">
<div class="col-md-12 panel">
<div class="col-md-12 panel-heading">
<h4>View Campaign:</h4>
</div>
<div id="imgContainer" class="col-md-12 panel-body">
<i class="fa fa-arrow-circle-left"></i>
#if(isset($img))
<div align="center">
<img src="{{($img)}}" />
</div>
#else
no data
#endif
</div>
</div>
</div>
#endsection
Goal is to get the base64 code to pass to the view.
Try replacing your foreach with the following code:
foreach($ref as $k1 => $key){
$item = $key->id; //change over here
//return var_dump($item);
$poster = $key->Poster; //change over here
//return var_dump($poster);
if($item == $id){ //change over here
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
I reckon, you would also have to update the function signature to look something like following:
public function viewCampaign(Request $request , $id){
//your code
}
I did as directed according to the answer provided to this question
but it didn't work for me . So i reasked this question.
my controller is
public function save() {
$med_group = MedicineGroup::create(Request::all());
if ($med_group) {
$this->setServerMessage('MedicineGroup created successfully');
return Redirect::to('admin/user/create')->with('flashmessage',$this->getServerMessage());
}
}
I have made setServerMessage() and getServerMessage() in Controller.php
public function setServerMessage($messagearray) {
if (is_array($messagearray)) {
$type = $messagearray['type'];
$html = "<div style='height:auto;padding:7px 0px 6px 20px;margin:0px' class = 'pull-left text-left col-md-8 alert alert-{$type}'>{$messagearray[0]}</div>";
} else {
$html = "<div style='height:33px;padding:7px 0px 6px 20px;margin:0px' class = 'pull-left text-left col-md-8 alert alert-info'>{$messagearray}</div>";
}
$temp = '';
if (\Session::get('SERVER_MESSAGE')) {
$temp = \Session::get('SERVER_MESSAGE');
}
\Session::put('SERVER_MESSAGE', $temp . $html);
}
public function getServerMessage() {
if (\Session::get('SERVER_MESSAGE')) {
$temp = \Session::get('SERVER_MESSAGE');
\Session::forget('SERVER_MESSAGE');
return $temp;
} else
return "";
}
my view is setup like this
<div class="box-footer text-right">
#include('flash')
<input type="submit" class="btn btn-success" value='Save'>
<input type="reset" class="btn btn-primary" value='Reset' />
Cancel
</div>
and in my flash.blade.php i have written
#if(isset($flashmessage))
{!! $flashmessage !!}
#endif
what did I miss? i followed this site too but i can't flash a message in my view.
Set the flash message and then redirect to desired route
Controller:
session()->flash('msg', 'Successfully done the operation.');
return Redirect::to('admin/user/create');
Now get the message the in view blade file
Blade
{!! Session::has('msg') ? Session::get("msg") : '' !!}
Try out this thing, I am replacing your entire code, you can change it according to your need:
public function save()
{
$med_group = MedicineGroup::create(Request::all());
if ($med_group) {
//$this->setServerMessage('MedicineGroup created successfully');
// flash method to be used when just printing the message
// on the screen. Link below
\Session::flash('key', 'Your message here...');
return Redirect::to('admin/user/create');
}
}
In your view file:
#if(Session::has('key))
{{ Session::get('key') }}
#endif
Link for more information
every other thing seems to be fine except for your layout
laravel would escape the variable you are passing into the session while using this
#if(isset($flashmessage))
**{!! $flashmessage !!}**
#endif
you should do this instead
#if(isset($flashmessage))
**{{ $flashmessage }}**
#endif