public function update(Request $request, $id)
{
$house = House::find($id);
$house->name = $request->name;
$house->code = $request->code;
$house->description = $request->description;
$house->address = $request->address;
$house->owner_name = $request->owner_name;
$house->manager_name = $request->manager_name;
if($house->update()){
return redirect()->route('houses')
->with('alert.status', 'success')
->with('alert.message', 'Successfully Updated.');
}
else{
return redirect()->route('houses')
->with('alert.status', 'danger')
->with('alert.message', 'Try Again.');
}
}
Here i want to update all my fields except code when the code already exists in the database.How can i do that please give some solution.Thank you in advance.
You can use the null coalescing operator, available in php version 7.
In short, you can do this:
public function update(Request $request, $id)
{
$house = House::find($id);
$house->code = $house->code ?? $request->code;
$house->save();
}
If $house->code is different from null, this will be used if it will not use $request->code.
https://www.tutorialspoint.com/php7/php7_coalescing_operator.htm
do this way with ternary condition :
public function update(Request $request, $id)
{
$house = House::find($id);
$house->code = !empty($house->code) && $house->code!= NULL ? $house->code : $request->code;
}
Use a if :
public function update(Request $request, $id)
{
$house = House::find($id);
$house->name = $request->name;
if($house->code == NULL)
$house->code = $request->code;
$house->description = $request->description;
$house->address = $request->address;
$house->owner_name = $request->owner_name;
$house->manager_name = $request->manager_name;
$house->save();
if($house->update()){
return redirect()->route('houses')
->with('alert.status', 'success')
->with('alert.message', 'Successfully Updated.');
}
else{
return redirect()->route('houses')
->with('alert.status', 'danger')
->with('alert.message', 'Try Again.');
}
}
You should use the save() method after you made all this changes.
You can check for code existence on database by Eloquent: Mutators like below on your House Model
class House extends Model
{
//your codes
public function setCodeAtrribute($value)
{
if ($this->attributes["code"] != null) $this->attributes["code"] = $value
}
}
You can also check here for more information
Related
I have this query in eloquent which I want to filter by dates but having a "WhereHas" or a "WhereIn" doesn't filter them anymore. any solution?
public static function filterForTransactions(Request $request, MarketAgreement $v_teleco, AgreementEnergia $v_energia) {
$v_teleco = $v_teleco->newQuery();
$v_teleco->where('user_id_inversor', \Auth::user()->id)
->orWhereHas('market_transaction', function($query){
$query->where('user_id_subaccount', \Auth::user()->id);
})
->orWhereIn('user_id', [$ids]);
if ($request->has('from') && $request->has('to') && $request->input('from') != null && $request->input('to') != null) {
$from = \Carbon\Carbon::parse($request->from)
->startOfDay()
->toDateTimeString();
$to = \Carbon\Carbon::parse($request->to)
->endOfDay()
->toDateTimeString();
$v_teleco->whereBetween('created_at', [$from, $to]);
}
return $v_teleco->orderBy('updated_at', 'desc')->get();
}
Thx so much
a few things to mention about your code
public static function filterForTransactions(Request $request, MarketAgreement $v_teleco, AgreementEnergia $v_energia)
{
/** #var Illuminate\Database\Eloquent\Builder $v_teleco */
$v_teleco = $v_teleco->newQuery();
// when you want to modify builder object you need to overwrite it
$v_teleco = $v_teleco->where('user_id_inversor', \Auth::user()->id)
->orWhereHas('market_transaction', function ($query) {
$query->where('user_id_subaccount', \Auth::user()->id);
})
->orWhereIn('user_id', [$ids]); // where do you get $ids?
if ($request->has('from') && $request->has('to') && $request->input('from') && $request->input('to')) {
$from = \Carbon\Carbon::parse($request->from)
->startOfDay()
->toDateTimeString();
$to = \Carbon\Carbon::parse($request->to)
->endOfDay()
->toDateTimeString();
// same here
$v_teleco = $v_teleco->whereBetween('created_at', [$from, $to]);
}
return $v_teleco->orderBy('updated_at', 'desc')->get();
}
this way it looks fine so if it still doesn't work please provide more details
I'm setting up a CRUD, similar to an ecommerce
I uploaded the image, it is stored in the public folder. The name of the image is replaced by the value of an input that the user places. This same value is saved in the database with the image extension.
I was also able to delete the image, but I don't know how to update it. Can someone please give me a light?
project controller:
public function store(Request $request)
{
$nameFile = $request->input('imageName', '');
if($request->file('imageFile')->isValid()){
$nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
$request->file('imageFile')->storeAs('projects', $nameFile);
}
$project = new Project();
$project->name = $request->input('name');
$project->price = $request->input('price');
$project->imageName = $nameFile;
$project->save();
return redirect()->route('ProjectControllerCreate');
}
public function destroy($id)
{
$project = Project::find($id);
// Image
$filePathName = public_path().'/storage/projects/'. $project->imageName;
if( file_exists($filePathName) ){
unlink($filePathName);
}
// Data
if(!$project)
return redirect()->back();
$project->delete();
return redirect()->route('ProjectControllerCreate');
}
public function update(Request $request, $id)
{
$project = Project::find($id);
if(!$project)
return redirect()->back();
$project->update($request->all());
return redirect()->route('ProjectControllerCreate');
}
This is how you can update :
use Illuminate\Support\Facades\Storage;
public function update(Request $request, $id)
{
$project = Project::find($id);
if(!$project)
return redirect()->back();
// Update new image
if($request->file('imageFile')->isValid()){
// Delete old image
$old_image = $project->imageName;
Storage::delete($old_image);
$nameFile = $request->input('imageName', '');
$nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
$request->file('imageFile')->storeAs('projects', $nameFile);
$project->imageName = $nameFile;
}
$project->name = $request->input('name');
$project->price = $request->input('price');
$project->save();
return redirect()->route('ProjectControllerCreate');
}
I have problem with edit and update with 2 table using query builder.
--->After i press button submit--->the data insert new row---> not update current data.
This is my function edit(only for view old data)
public function edit(Request $request, $id){
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$country = Country::all();
$geo_zones = GeoZone::all();
//dd($tax_rate);
//dd($tax_rate_details);
//dd($geo_zones);
if(!$tax_rate) {
return redirect('/');
}
return view('tax_management.edit',['country' => $country , 'tax_rate'=>$tax_rate , 'geo_zones'=>$geo_zones, 'tax_rate_details'=>$tax_rate_details]);
}
This is my update(i do validation and the saveTax is the saving part)
public function update(Request $request, $id){
$this->validate($request,[
'country_id'=> 'required',
'tax_type' => 'required',
'name' => 'required|max:100',
'code' => 'required|max:50'
]);
//dd($request->input());
DB::beginTransaction();
try{
$tax_rate = TaxRate::find($id);
$tax_rate_details = TaxRateDetail::where('tax_rate_id', $id)->get();
$this->saveTax($request, $tax_rate);
DB::commit();
return redirect()->route('tax_management.index');
} catch (\Exception $ex){
//dd($ex);
DB::rollback();
return back()->withInput()->withErrors('Fail to save');
}
}
This is my function save()
private function saveTax(Request $request, $tax_rate){
$tax_rate->country_id = $request->input('country_id');
$tax_rate->geo_zone_id = $request->input('geo_zone_id');
$tax_rate->tax_type = $request->input('tax_type');
$tax_rate->name = $request->input('name');
$tax_rate->code = $request->input('code');
$tax_rate->description = $request->input('description');
if(!empty($request->input('active'))){
$tax_rate->active =1;
} else {
$tax_rate->active =0;
}
$tax_rate->save();
if($tax_rate->tax_rate_id) {
TaxRateDetail::where('tax_rate_id', $tax_rate->tax_rate_id)->delete();
}
if($request->input('tax_rate_details')){
foreach ($request->input('tax_rate_details') as $key => $value) {
$tax_rate_detail = new TaxRateDetail();
$tax_rate_detail->tax_rate_id = $tax_rate->tax_rate_id;
$tax_rate_detail->priority = $value['priority'];
$tax_rate_detail->date_from = $value['date_from'];
$tax_rate_detail->date_to = $value['date_to'];
$tax_rate_detail->rate = $value['rate'];
$tax_rate_detail->type = $value['type'];
$tax_rate_detail->active = $value['active'];
//dd($tax_rate_detail);
$tax_rate_detail->save();
}
}
}
I want to save edit update with old(id). not create new. Please help thank you. I don't know where the code gone wrong.
When trying to filter with only username or email code works fine.But when i am trying to filter with both email and username it returns empty.what i am missing
User model
public function scopeEmail($query, $email)
{
$query->where('email','=', $email);
}
public function scopeUsername($query, $username)
{
$query->where('username','=', $username);
}
Controller:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q->Email($request->input('email'));
}
if (isset($username))
{
$q->Username($request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use When to make filter easy:
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
$q->when($email,function ($query){
$query->where('email',$email);
});
$q->when($username,function ($query){
$query->where('username',$username);
});
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Use simple where in if statements
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (isset($email))
{
// simple where here or another scope, whatever you like
$q = $q->where('email', $request->input('email'));
}
if (isset($username))
{
$q = $q->where('username', $request->input('username'));
}
//execute
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Try this
public function filter(Request $request)
{
$q = User::query();
$email = $request->input('email');
$username= $request->input('username');
if (!is_null($email))
{
$q = $q->where('email', $email);
}
if (!is_null($username))
{
$q = $q->where('username', $username));
}
$results = $q->get();
return response()->json(['issError'=>0, 'errorCode'=>0,'message'=>$results],200);
}
Please help guys, I have encrypted successfully my password with password_hash but is there any solution how to check login and password using PHP password_verify for multiuser login?
here's my controller:
public function index()
{
$this->form_validation->set_rules('email','Email address','required');
$this->form_validation->set_rules('password','Password','required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('view_login');
} else {
$this->load->model('Model_members');
$valid_user = $this->Model_members->check_credential();
if($valid_user == FALSE)
{
$this->session->set_flashdata('error','');
redirect("login");
} else {
$this->session->set_userdata('email', $valid_user->email);
if($this->session->userdata('groups') == '1')
{
redirect('home');
}
elseif($this->session->userdata('groups') == '2')
{
redirect('homepage');
}
elseif($this->session->userdata('groups') == '0')
{
redirect('test1');
}
}
}
}
This is my model:
public function check_credential()
{
$email = set_value('email');
$password = set_value('password');
$hasil3 = $this->db->where('email', $email)
->where('password', $password)
->limit(1)
->get('users');
if($hasil3->num_rows() > 0)
{
return $hasil3->row();
} else {
return array();
}
}
Very appreciate for the help !!
Please find below mentioned solution, It will help you.
In Controller
$userData['email'] = $this->input->post('email');
$userData['password'] = $this->input->post('password');
$valid_user = $this->Model_members->check_credential($userData);
In Model your function will look like below.
public function check_credential($param) {
$hasil3 = $this->db->where('email', $param['email'])
->where('password', password_hash($param['password'], PASSWORD_DEFAULT, ['cost' => 10]))
->limit(1)
->get('users');
if ($hasil3->num_rows() > 0) {
return $hasil3->row();
} else {
return array();
}
}
Let me know if it not work.
Controller
//create array to pass data to model
$data = [
'email' => $this->input->post('email'),
'password' => $this->input->post('password')
];
//check model to see if user exists and if correct password
$user = $this->name_of_model->check_credential($data);
if(isset($user['error])){
//return error message in some form
}
Model:
You want to break you process in two, in order to make error reporting better. First check if user exists, then check if password is correct
public function check_credential($data) {
//see if user exists first
$user = $this->db->where('email', $data['email'])
->get('users')->row_array();
if($user){
$success = (password_verify($data['password'],$user['password']));
return ($success) ? $user : ['error'=>'Incorrect Password']
}
else{
return ['error'=>'User doesn't exist'];
}
}