Laravel Insert data without select file - php

Ok, when insert data in the database, in the form of my field is to image, but if you insert data without image, appears to me the following error.
Call to a member function getClientOriginalName() on a non-object
public function store() {
$unos = Input::all();
$obavezno = array('name' => 'required',
'number' => 'required|unique:os',
'zajednica' => 'required',
'slika' => 'image|size:3000',
);
$valid = Validator::make($unos, $obavezno);
if($valid->passes()) {
$biraci = new Biraci();
$filename = Input::file('slika')->getClientOriginalName();
$biraci->name = Input::get('name');
$biraci->slika = Input::file('slika')->move('public/uploads', $filename);
$biraci->path = $filename;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
return Redirect::to('biraci/dodaj')->with(array('ok' => 'Birac je uspjesno dodat.'));
} else {
return Redirect::to('biraci/dodaj')->withErrors($valid);
}
}

Try this:
if($valid->passes()) {
$biraci = new Biraci();
if (Input::hasFile('slika')) {
$filename = Input::file('slika')->getClientOriginalName();
}
$biraci->name = Input::get('name');
$biraci->slika = isset($filename) ? Input::file('slika')->move('public/uploads', $filename); : null;
$biraci->path = isset($filename) ? $filename : null;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
}

$filename = Input::file('slika')->getClientOriginalName();
// change to
$filename = Input::hasFile('slika') ? Input::file('slika')->getClientOriginalName() : null;

Related

Problem of Curly Brackets in my controller Php Symfony

I want to call my function but when I call it I have a problem with curly Brackets at the end of my code and i have this error Error SYMFONY ( {} ) in my Controller.
I have no idea where to put them for my code to work. I have this problem when I add my function that allows me to retrieve the
history of the action. The mentioned function goes as this:
$this->logHistory->addHistoryConnection($project->getId(), $user->getId(), 'Delete Local Suf', $sf_code);
Function Supp Suf
/**
* #Route("/creation/suf/supp", name="suf_supp")
*/
public function suf(
Request $request,
ShapesRepository $shapesRepository
) {
$params = $this->requestStack->getSession();
$projet = $params->get('projet');
$modules = $params->get('modules');
$fonctionnalites = $params->get('fonctionnalites');
$user = $this->getUser()->getUserEntity();
$manager = $this->graceManager;
$mapManager = $this->mapManager;
$countElements = $mapManager->getCount();
$shapes = $shapesRepository->findBy(array('projet' => $projet->getId()));
$adresseWeb = $this->getParameter('adresse_web');
$carto = $params->get('paramCarto');
$centrage = $params->get('centrage');
$cableColor = $params->get('cableColor');
$sf_code = '';
if ($request->get('suf') != '') {
$sf_code = $request->get('suf');
}
$suf = $manager->getSuf($sf_code);
$success = '';
$error = '';
$warning = '';
if ($request->query->get('success')) {
$success = $request->query->get('success');
} elseif ($request->query->get('error')) {
$error = $request->query->get('error');
} elseif ($request->query->get('warning')) {
$warning = $request->query->get('warning');
}
if ($request->isMethod('POST')) {
if ($request->request->get('sf_code') != '') {
$sf_code = $request->request->get('sf_code');
}
if ($request->get('val') != '') {
$val = $request->get('val');
}
$dir = $this->getparameter('client_directory');
$dossier = str_replace(' ', '_', $projet->getProjet());
$dir = $dir . $dossier . '/documents/';
$cable = $val[0];
$chem = $val[1];
$t_suf = $this->graceCreator->supprimeSuf($sf_code, $cable, $chem);
if ($t_suf[0][0] == '00000') {
$this->logHistorique->addHistoryConnection($projet->getId(), $user->getId(), 'Suppression Suf Local', $sf_code);
// $creator->delDirObjet( $st_code, $dir );
$data = new JsonResponse(array("success" => "create!"));
return $data;
} else {
$data = new JsonResponse(array("error" => "Error : " . $t_suf));
return $data;
}
return $this->render('Modifications/supSuf.html.twig', array(
'user' => $user,
'paramCarto' => $carto,
'cableColor' => $cableColor,
'suf' => $suf,
'adresseWeb' => $adresseWeb,
'centrage' => $centrage,
'shapes' => $shapes,
'projet' => $projet,
'modules' => $modules,
'fonctionnalites' => $fonctionnalites,
'countElements' => $countElements
));
}
}
Your only return statement is inside of an if condition. If the code does not pass the condition, it has nothing to return. The code must return something in all possible cases. If you are not still used to these practices, an IDE might guide you until it becomes a routine. PHPStorm is my personal preference.
BTW, I recommend you to switch from the array() syntax to the more globally accepted [] although you must be in PHP 5.4 or higher.

ArgumentCountError when updating content in larvel

In my laravel application, I'm trying to update some content using the following controller function. But every time when I try to run the following function am getting an error
public function update_tcp(Request $request, $id)
{
try{
Session::put('tcpSession', '1');
$request->merge(['gender' => 'M']);
$this->validate($request, [
'first_name_tcp2' => 'required',
'last_name_tcp2' => 'required',
'image_id' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'user_id'=>'required',
'gender'=>'required',
'date_of_birth_tcp2'=>'required'
]);
//$input = $request->except('_method', '_token');
$input = $request->all();
unset($input['_token']);
unset($input['_method']);
if ($image = $request->file('image_id')) {
$destinationPath = 'propics/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image_id'] = "$profileImage";
//dd($profileImage);
}else{
//unset($input['image']);
$profileImage='default-avatar.png';
$request->merge(['image_id' => 'default-avatar.png']);
}
$data = $request->input();
$tcp = TakeCarePerson::WHERE('id','=',''.$id.'');
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->update();
return redirect()->route('participants.index')
->with('success',__('texts.Take care person updated successfully.'));
} catch(Exception $e){
return back() ->with('failedTcp',__('texts.Le fichier sélectionné doit être une image.'));
}
}
This is the error,
ArgumentCountError Too few arguments to function
Illuminate\Database\Eloquent\Builder::update(), 0 passed
Where do I need to fix in order to function my update function properly?
You are not passing data to update .Instead where find by id and then call save()
$tcp = TakeCarePerson::find($id);
$tcp->first_name = $data['first_name_tcp2'];
$tcp->last_name = $data['last_name_tcp2'];
$tcp->date_of_birth = $data['date_of_birth_tcp2'];
$tcp->user_id = $data['user_id'];
$tcp->image_id = $profileImage;
$tcp->gender= $data['gender'];
$tcp->save();
or
$tcp = TakeCarePerson::where('id','=',$id)->update([
'first_name'=> $data['first_name_tcp2'],
'last_name'=>$data['last_name_tcp2'],
'date_of_birth'=>$data['date_of_birth_tcp2'],
'user_id'=>$data['user_id'],
'image_id'=>$profileImage,
'gender'=>$data['gender']
]);

Update query laravel return false result and nothing error show why?

i'm working with laravel project, and i have an issue that is update query result return false value if i update with the same data, how to solve this? do i have to validate first before run the query and send a notification that the data is the same?
well this is my codes
public function update(Request $request)
{
$kamar_id = $request->input('kamar_id');
$title = $request->input('title');
$content = $request->input('content');
$keyword = $request->input('keyword');
$description = $request->input('description');
$prolog = $request->input('prolog');
$path = $request->input('path');
$sort = $request->input('sort');
$status = $request->input('status');
$type = $request->input('type');
$user_id = $request->input('user_id');
if (empty($request->input('path'))) {
$path = serialize(array('data/def.png'));
}else{
$path = serialize(explode(',', $request->input('path')));
}
$data = array('title' => $title,
'content' => $content,
'keyword' => $keyword,
'description' => $description,
'prolog' => $prolog,
'path' => $path,
'sort' => $sort,
'status' => $status,
'type' => $type,
'user_id' => $user_id);
// echo($kamar_id);
$update = Kamar::where('kamar_id',$kamar_id)->update($data);
if ($update) {
$response['status'] = 1;
}else{
$response['status'] = 0;
}
return response()->json($response);
}
thanks for helping me
Laravel Eloquent Update method returns true if anything updated in database from your query and return false if nothing is updated in database from your query.
refer:
https://laravel.com/docs/5.8/eloquent#updates
!nullTry
$update = Kamar::where('kamar_id','=',$kamar_id)->first();
if (!null($update))
{
$update->title = $title;
$update->content = $content;
$update->keyword = $keyword;
$update->description = $description;
$update->prolog = $prolog;
$update->path = $path;
$update->sort = $sort;
$update->status = $status;
$update->type = $type;
$update->user_id = $user_id;
$update->save();
$response['status'] = 1;
}
else
{
$response['status'] = 0;
}
Try using this
$kamarObj = new Kamar();
$kamarData = $kamarObj->find($kamar_id);
$result = $kamarData->update($data);
You can force updated_at column to be updated (or you can create this column if you don't have). So the query will be always updated.

Laravel : Update field when value is exist

I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}

How to Indent Laravel controller, view code?

One of my project needs code indentation, it has many of controller files looking like below code.
so basically I want to do is format code which should be done automatically without changing each file manually.
Controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
use File;
use Html;
use DB;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;
use Validator;
use Datatables;
use AppHelper;
use LaraCore;
use Image;
use App\Models\Customer;
use App\Models\_List;
use Carbon;
class CustomerController extends Controller
{
public function validator(array $data, $id = NULL)
{
$email_Rules = explode(',',"required,email,unique");
$email_Rules['unique'] = Rule::unique('customers')->ignore($id);
if(($key = array_search('unique',$email_Rules)) !== false) {
unset($email_Rules[$key]);
}
return Validator::make($data, [
'secret_key' => 'required|min:6|max:10',
'email' => $email_Rules,
'first_name' => 'required|alpha_num',
'city' => 'required',
]
);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('panel.customers.index');
}
public function create()
{
$data = array();
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
return view('panel.customers.create',$data);
}
public function edit($id,Request $request)
{
$data = array();
$Dates = array();
$customers = Customer::findOrFail($id);
$data['customers'] = $customers;
$EmployeeType = _List::where('list_name','=','EmployeeType')->pluck('item_name','id')->all();
$data['EmployeeType'] = $EmployeeType;
$preference= explode(',',$customers->preference);
$customers->preference = $preference;
$Category = _List::where('list_name','=','Category')->pluck('item_name','id')->all();
$data['Category'] = $Category;
if($customers->ready!=''){
$ready= explode(',',$customers->ready);
$customers->ready = $ready;
}
if($customers->approved!=''){
$approved= explode(',',$customers->approved);
$customers->approved = $approved;
}
$Name = explode(',','start_date,end_date');
$Dates[0] = new Carbon($customers->$Name[0]);
$Dates[1] = new Carbon($customers->$Name[1]);
$data['start_dateend_date'] = $Dates[0]->format('m/d/Y').' - '.$Dates[1]->format('m/d/Y') ;
return view('panel.customers.create',$data);
}
public function store(Request $request,$id="")
{
$this->validator($request->all(),$request->id)->validate();
if($request->id == null || $request->id == ""){
$inputs = $request->all();
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}else{
$inputs['ready'] = "";
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$nameArr = explode(',',$key_file);
$file = $value_file;
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
}
Customer::create($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
else{
$customers = Customer::where(['id'=>$request->input('id')])->first();
$inputs = $request->except('_token');
if($request->has('secret_key')){
$secret_key = bcrypt($request->secret_key);
$inputs['secret_key'] = $secret_key;
}
if($request->has('preference')){
$preference = implode(',',$request->preference);
$inputs['preference'] = $preference;
}
if($request->has('ready')){
$ready = implode(',',$request->ready);
$inputs['ready'] = $ready;
}
if($request->has('start_date,end_date')){
$Dates = explode('-',$request->input('start_date,end_date'));
$Name = explode(',','start_date,end_date');
$inputs[''.$Name[0]] = $Dates[0];
$Dates[0] = new Carbon($Dates[0]);
$Dates[1] = new Carbon($Dates[1]);
$inputs[''.$Name[0]] = $Dates[0]->format('Y-m-d');
$inputs[''.$Name[1]] = $Dates[1]->format('Y-m-d');
//dd($inputs);
}
foreach($request->files as $key_file => $value_file){
$destinationPath = 'public/uploads/customers';
\File::makeDirectory($destinationPath,0775,true,true);
$nameArr = explode(',',$key_file);
$OldFile = $customers->$nameArr[1];
if($OldFile!=''){
$OldFile = $destinationPath.'/'.$OldFile;
if(\File::exists($OldFile)){
\File::delete($OldFile);
}
}
$file = $value_file;
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$encrypted_name = md5(uniqid().time()).".".$extension;
$file->move($destinationPath,$encrypted_name);
$inputs[''.$nameArr[0]] = $name;
$inputs[''.$nameArr[1]] = $encrypted_name;
$SavedFile = $destinationPath.$encrypted_name;
}
$customers->update($inputs);
return redirect()->route('customers.index')->with('success',"Customer Saved successfully");
}
}
public function listCustomer(Request $request)
{
$customers = Customer::all();
$datatables = Datatables::of($customers)
->addColumn('actions', function($customers){
$html = '';
$html .= '<i class="fa fa-edit"></i>';
$html .= '<i class="fa fa-trash"></i>';
return $html;
})
->setRowId('id');
return $datatables->make();
}
public function destroy($id)
{
$customer = Customer::find($id);
$customer->delete();
return response()->json(array(
"status" => "success",
"message" => "Customer Deleted Successfully",
));
}
}
Maybe you could call a php beautifier on the file you created ? http://pear.php.net/package/PHP_Beautifier/
Note : you can call a command with exec
exec("php_beautifier $filename $filename");
It is hard to tell without more of your source but I imagine expressions like explode(',', $value["dbfield"] )[0] are catching some sort of tab character or importing blank fields that are somehow translated into spaces or tabs and causing the unwanted spacing.
#foreach($fields as $key => $value)
#if($value['dbfield'] == '')
#continue
#endif
#if($value['validation'])
#if(in_array('unique',explode(',',$value['validation'])))
'{{$value['dbfield']}}' => ${{$value['dbfield']}}_rules,
#else
#if(strpos($value["dbfield"],","))
'{{ explode(',', $value["dbfield"] )[0] }}' => '{{str_replace(',', '|', $value['validation'])}}',
#else
'{{$value['dbfield']}}' => '{{str_replace(',', '|', $value['validation'])}}',
#endif
#endif
#endif
#endforeach

Categories