How to update multiple image and remove old images in Laravel 5.4? - laravel-5.4

It is difficult for me to update and replace several images. How to save multiple images, I understand, but I can not update and remove old images.
The are 3 tables:
portfolios
photos
portfolio_photo (pivot)
HTML Form Update
{!! Form::model($portfolio, ['route' => ['portfolio.update', $portfolio->id], 'method' => 'PUT', 'files' => 'true' ]) !!}
<input type="file" id="portfolio_photos" name="portfolio_photos[]" class="form-control" multiple>
{{!! Form::close() !!}}
Controller, I do not know how to do a method update.
public function store(PortfolioValidation $request){
$portfolio = new Portfolio();
$portfolio->portfolio_title = $request->portfolio_title;
$portfolio->portfolio_slug = str_slug($request->portfolio_title);
$portfolio->apartment_project = $request->apartment_project;
$portfolio->apartment_area = $request->apartment_area;
$portfolio->type_repair = $request->type_repair;
$portfolio->year_implementation = $request->year_implementation;
$portfolio->deadline = $request->deadline;
$portfolio->save();
if($request->hasFile('portfolio_photos')){
foreach($request->portfolio_photos as $portfolio_photo){
$fileName = rand() . '.' . $portfolio_photo->getClientOriginalExtension();
$path = public_path('img/portfolio/' . $fileName);
Image::make($portfolio_photo)->resize(1280, 960)->save($path);
$newFile = new Photo();
$newFile->portfolio_photos = $fileName;
$newFile->save();
$portfolio->photos()->save($newFile);
}
}
Session::flash('success', 'Success!');
return redirect()->route('portfolio.index');
}

Related

Having issue while updating the records in laravel it is showing page not found

I have three table accidents, vehicle and people. I am performing curd operation but I am not able to update as there are multiple rows and columns. Can you please check the routes and actually idk the correct way of updating
public function edit($id)
{
$resultset = DB::select('select * from accidents where id = ?',[$id]);
$vehicle = DB::table('vehicle')
->select(['vehicle.type', 'vehicle.details', 'vehicle.vehicleno', 'people.age', 'people.gender', 'people.status'])
->join('people','people.vehicle_id','=','vehicle.id')
->where('people.accidents_id','=',$id)
->get();
return view('updaterecord', array('accident'=>$resultset,'vehicle'=>$vehicle));
}
public function update($id)
{
$branch = $request->input('branch');
$roadname = $request->input('roadname');
$caseregister = $request->input('casereg');
$description = $request->input('description');
$ipc_mvact =$request->input('ipc_mvact');
$type = $request->input('vehicletype');
$vehicleno = $request->input('vehicleno');
$vehicledetails = $request->input('vdetails');
$age=$request->input('age');
$gender=$request->input('gender');
$status=$request->input('status');
DB::update('update acidents set branch = ?, roadname=? ,casereg=?, description=?, IPC_MVAct_Sections=? where id = ?',[$branch,$roadname,$caseregister,$description, $ipc_mvact,$id]);
DB::update('update vehicle set type = ?, vehicleno=? ,vehicledetails=? where accidents_id = ?',[$type,$vehicleno,$vehicledetails,$id]);
DB::update('update people set age = ?, gender=? ,status=? where accidents_id = ?',[$age,$gender,$status,$id]);
return redirect('/admin/tables');
}
// Routes
Route::namespace('Auth')->group(function () {
Route::get('/login', '\App\Http\Controllers\AdminController#index');
Route::post('/admin', '\App\Http\Controllers\AdminController#checklogin');
Route::get('/admin/dashboard', '\App\Http\Controllers\AdminController#successlogin');
Route::get('/admin/tables', '\App\Http\Controllers\AdminController#showtable');
Route::get('/admin/tables/viewrecord/{id}', '\App\Http\Controllers\AdminController#viewaccident');
Route::get('/admin/tables/editrecord/{id}', '\App\Http\Controllers\AdminController#edit');
Route::post('/admin/tables/edit/{id}', '\App\Http\Controllers\AdminController#update');});
//form
<form action="/edit/<?php echo $accident[0]->id; ?>" method="POST">
You have error in action url .so for better usage i have added named route for updates like below
Route::post('/admin/tables/edit/{id}', '\App\Http\Controllers\AdminController#update')->name('adminUpdate');
in your form action
<form action="{{route('adminUpdate',[$accident[0]->id])}}" method="POST">

Yii2 Dynagrid: How to implement Sortable to sort the rows

In Dynagrid it is possible to use Sortable to sort the columns. I need to enable sorting rows, which should work similarly:
Is there a way to implement such sorting directly in Dynagrid or do I have to programm the sorting separately?
To enable the sorting is simple:
$('tbody').sortable();
The only problem is to save the sorting to the database. I have decided to save it after a click on a button (and not with ajax) in views/sorted-table/index.php:
if (strpos(Url::current(), 'sort') === false) {
$form = ActiveForm::begin([
'id' => 'sort-form',
]);
echo '<input type="hidden" id="field-sort" name="sort" value="">';
if (isset($sortMessage) && $sortMessage != '') {
echo '<p>' . $sortMessage . '</p>';
}
echo Html::submitButton(Icon::show('floppy-o') . 'Sortierung speichern', ['class' => 'btn btn-primary']);
ActiveForm::end();
DynagridSortAsset::register($this);
}
The positions of rows are saved in the hidden input field by jQuery:
$('.btn-primary').mousedown(function() {
var sorting = "";
$('.sortable-row').each( function (index, value) {
sorting += $(this).attr('data-id') + ':' + $(this).attr('data-sortierung') +',';
});
$('#field-sortierung').val(sorting);
});
The values are then in controller processed and saved to the database.

Saving check boxes choices with Perl and PostgreSQL

I'm trying to create a user's preference page that has a bunch of check boxes letting the user decide how they want to receive their notifications. Here is my current HTML form for preferences:
<form method="post">
<table id="preferences" class = "preferences">
<tr class="headers">
<th class = "preferences">Preference</th>
<th class = "preferences">Value</th>
<th class = "preferences">Notification Preferences</th>
</tr>
<tr>
<td class = "preferences">Default Post Markup</td>
<td class = "preferences">
<select name="default_markup">
<% foreach(USystem::Markup->markup_types) {
print Usystem::Utils::option_tag($_->{id}, $_->{name}, $prefs->value(1));
} %>
</select>
</td>
<td>
<input type = "checkbox" name = "notification-option" id = "all-post"> All Posts <br/>
<input type = "checkbox" name = "notification-option" id = "others-post"> Other's Posts <br/>
<input type = "checkbox" name = "notification-option" id = "client-post"> Cilent's Post <br/>
<input type = "checkbox" name = "notification-option" id = "assign-post"> Task Assigned
</td>
</tr>
<tr>
<th colspan="3" class="submitrow"><input type="submit" name="submit" value="Save Preferences" /></th>
</tr>
</table>
</form>
I just added the 4 checkboxes and I need help saving them into the database where I use a boolean to determine if they are checked or not.
My Perl script on the HTML page that runs when the "Save Preferences" button is selected:
my $form = $Request->Params;
my $prefs = USystem::UserPrefs->new($user->userid);
if($Request->{Method} =~ /POST/i) {
my $dbh = USystem::DB->new;
if($form->{submit} eq "Save Preferences") {
$prefs->value($USER_PREF_MARKUPTYPE, $form->{default_markup});
$prefs->update;
}
$Response->Redirect('/preferences');
}
the $Request->Params is basically the same as CGI->Params()
this is UserPrefs:
package USystems::UserPrefs;
use strict;
use USystems::DB;
sub new {
my $self = shift;
my $class = ref($self) || $self;
my $userid = shift;
$self = bless {}, $class;
$self->{dbh} = USystems::DB->new;
if($userid) {
$self->userid($userid);
$self->__populate;
}
return $self;
}
sub __populate {
my $self = shift;
my $sth = $self->{dbh}->prepare("select prefid, value from user_preferences where userid=?");
$sth->execute($self->userid);
while(my $href = $sth->fetchrow_hashref()) {
$self->value($href->{PREFID}, $href->{VALUE});
}
$sth->finish();
}
sub update {
my $self = shift;
my $sth = $self->{dbh}->prepare("delete from user_preferences where userid=?");
$sth->execute($self->userid);
$sth->finish;
$sth = $self->{dbh}->prepare("insert into user_preferences(userid, prefid, value) values(?, ?, ?)");
while(my ($prefid, $value) = each %{$self->{PREFS}}) {
$sth->execute($self->userid, $prefid, $value);
}
$sth->finish;
}
sub userid {
my $self = shift;
$self->{USERID} = shift if(#_);
$self->{USERID};
}
sub value {
my $self = shift;
my $prefid = shift;
$self->{PREFS}->{$prefid} = shift if(#_);
return $self->{PREFS}->{$prefid};
}
1
How would I go about storing the values of whether the check boxes are checked or not as well as update my current Perl script to take in the values. I'm pretty new to Perl haven't had much luck. I'd be great if you can give an explanation to why you did what you did too.
Please let me know if there's more information you need. Thanks
The line
my $prefs = USystem::UserPrefs->new($user->userid)
creates a new object and copies the current preferences for that user from the database. Afterwards you can acccess or update individual preferences using $prefs->value(value_name [, new_value), and a call to $prefs->update will copy the current values back to the database
You already have
$prefs->value($USER_PREF_MARKUPTYPE, $form->{default_markup})
and you need to add more calls like that to set the values for other preferences before you call
$prefs->update
to save them all

How to display a div in a post in your category page - wordpress

I have a website where each post is displayed and each post has a description explaining the post.
How can I get my category page (the page that summarises all posts) to show only the small summary of the post and nothing else. At the moment I am using
the_excerpt();
but this limits the text to 55 words, however some are smaller than that, and so other text is displayed in the category that I don’t want.
For example, this is an example post:
http://thestudentbubble.com/hidden-gems/hidden-gems-restaurants/ganges-indian/
As you can see below the description is additional information which I don't want it to appear on the category page.
this is the category page - http://thestudentbubble.com/hidden-gems/hidden-gems-restaurants/
yet the additional information that I don't want to appear still appears.
The text I want to appear is in:
<div class = "bioText">
How can I make only the text in the div appear in the category page?
Thank you for the help!
this is the category loop :
<div class="comment">
<?php
$cats = get_the_category();
$category_id = $cats[0]->cat_ID;
$args = array( 'posts_per_page' => 1, 'category' => $category_id);
$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) :
$this_post_ID = get_the_ID();
$this_post_preview = get_post_meta( $this_post_ID, 'post_preview', true );
echo $this_post_preview;
//the_excerpt();
//the_content();
wp_reset_postdata();
endforeach;
?>
</div>
Ok then, the first thing to do is to create a custom textarea in each post's admin panel. It will appear under the editor. Let's create the .php file that will contain our code, call it post_preview_field.php, and place it in the theme root folder. After doing that, we will need to reference it in our functions.php file. This is done by simply adding the following line:
require_once(get_template_directory().'/post_preview_field.php');
Let's open our post_preview_field.php file and write the code.
<?php
add_action( 'add_meta_boxes', 'post_preview_metabox' );
add_action( 'save_post', 'post_preview_save_postdata' );
function post_preview_metabox() {
$screens = array( 'post' );
foreach ($screens as $screen) {
add_meta_box(
'post_preview_metabox_id',
__( 'Post Preview', 'post_preview_textdomain'),
'post_preview_inner_boxes',
$screen
);
}
}
function post_preview_inner_boxes( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'post_preview_noncename' );
$post_preview_value = get_post_meta( $post->ID, 'post_preview', true );
echo '<label for="post_preview_new_field">';
_e("", 'post_preview_textdomain' );
?>
</label>
<textarea name="post_preview_new_field" id="post_preview_new_field" ><?php echo $post_preview_value; ?></textarea>
<?php }
function post_preview_save_postdata( $post_id ) {
if ( 'post' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return;
} else {}
if ( ! isset( $_POST['post_preview_noncename'] ) || ! wp_verify_nonce( $_POST['post_preview_noncename'], plugin_basename( __FILE__ ) ) )
return;
$post_ID = $_POST['post_ID'];
$post_preview = ( $_POST['post_preview_new_field'] );
add_post_meta($post_ID, 'post_preview', $post_preview, true) or
update_post_meta($post_ID, 'post_preview', $post_preview);
}
?>
Here we go. We just created a textarea field that appears in every post's panel, can contain some text, is saved every time we save\update the post and is stored in the post's metadata.
Now, all we have to do is access this value in the frontend and echo it. How do we do that?
In the loop, we first assign the post ID to a variable:
$this_post_ID = get_the_ID();
and then assign the data we stored to another:
$this_post_preview = get_post_meta( $this_post_ID, 'post_preview', true );
That's it. We can now echo the preview:
echo $this_post_preview;
I managed to solve it by adding
<!--more-->
after each of the descriptions.

Dynamically created checkboxes using ajax from sql result set

I am looking to use ajax to dynamically create checkboxes each time you change your selection from a <select> tag, see the below screenshot for a section of the form that is relevant:
NOTE: The checkboxes under "Queues" should be dynamic.
At the moment, when you change the value for Team it grabs the team name (in this case "Test"), then using ajax (POST) it returns the Manager name for that team.
What I want it to do is look up another table that has a list of the "queues" associated with each team; I am going to add an "onchange" attribute in the tags for the "Manager Name" field.
Below is the code I'm currently using to accomplish the Team => Manager Name dynamic filling:
<script>
window.onload = function() {
getManager($("#team").val());
}
function getManager(team) {
$.ajax({
type: "POST",
url: "getManager.php",
data: {team:team}
}).done(function( manager ) {
$("#manager_name").val(manager);
});
}
</script>
And here is the getManager.php file that it uses:
<?php
require("../../database/db.php");
$mysqli = new db("nab_reporting");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$team=$mysqli->real_escape_string($_POST['team']);
$result = $mysqli->query("SELECT manager_name FROM team WHERE teamname = '".$team."'");
$row = $result->fetch_assoc();
echo $row['manager_name'];
mysqli_close($mysqli);
?>
Keeping in mind that the above works; I now need a way to use the onchange attribute of the Manager Name field that will use ajax (similar to above), passing another php page the value that is currently in the field (in this case Kane Charles) and will return a result set (array or JSON maybe?) containing a list of all queues in the database that match up with that Team name.
Below is the html code for each of the different bits:
TEAM
<select name="team" id="team" required="required" onchange="getManager(this.value)">
<?php
include(__DIR__ . "/../../database/db.php");
$db = new db("nab_reporting");
$result = $db->query("SELECT teamname FROM team");
while ($row = $result->fetch_assoc()) {
echo "
<option value=\"" . $row['teamname'] . "\">" . $row['teamname'] . "</option>
";
}
$db->close();
?>
</select>
MANAGER NAME
<input type="text" name="manager_name" id="manager_name" required="required" onchange="getQueues(this.value)">
QUEUES
<label>
Queues
</label>
<div id="queue_options">
<!-- queues dynamically created here -->
</div>
I need the contents of queue-options to be erased and reset to only the queues associated with the current team; I haven't done a great deal with ajax, hence why I'm posting on here.
This revision should match what you are asking about
PHP
// make an array to hold the queues
$data = Array();
// Fetch the rows of all the queues
$res = $mysqli->query("SELECT * FROM the_queue_table WHERE manager='" . $_GET["manager"] . "'");
// loop through all the rows and push the queues into the data array
while(($row = mysql_fetch_object($res)) !== false)
{
array_push($data, $row->queue);
}
// return the data array as a json object
echo json_encode($data);
JavaScript
// get the page and send the manager name to filter with
$.get("file.php?manager=" + managerName, function(page)
{
// parse the json into an object
var data = $.parseJSON(page);
// remove existing checkboxes
$("#queue_options").children().remove();
// add checkboxes to the div
for (var item in data){
$("#queue_options").append("<input type=\"checkbox\" value=\"" + item + "\" />" + item + "<br />");
}
});