PHP how to Compare Form inputs with database values | Laravel - php

i need to compare Database Values with the inputs from Form this a a part of my code
public function update($id, Request $request)
{
$requestData = $request->all();
$website_info = WebsiteInfos::findOrFail($id);
if ( $website_info->all() == $request->all()) {
Session::flash('alert-info', 'No Change have been made');
return redirect('admin/website_infos');
} else {
$website_info->update($requestData);
Session::flash('alert-success', 'WebsiteInfos updated!');
return redirect('admin/website_infos');
}
}
i need to compare $request->all() with db value ! i try this ! the if is ignored and always Show me the Success alert

The simplest way to do this is to find the record in a query.
$website_info = WebsiteInfos::where([
['id', '=' ,$id],
['name', '=', $request->name],
['email', '=', $reqest->email]
])->first();
if ($website_info != null) {
Session::flash('alert-info', 'No Change have been made');
return redirect('admin/website_infos');
} else {
$website_info->update($requestData);
Session::flash('alert-info', 'No Change have been made');
return redirect('admin/website_infos');
}

I would do this. Database record can never be equal to the incoming request because of the presence of primary key, date or foreign keys. You should pluck database values you want to compare with the request as follows
$db_records =$website_info->pluck(['name', 'url','any_other_field'])->toArray();
$incoming_request =$request->all(); //assumes this contains name, url, and any_other_field
if ( $db_records == $incoming_request) {
Session::flash('alert-info', 'No Change have been made');
return redirect('admin/website_infos');
}

Related

what is the correct way to pass 3 where () conditions in the same function, multiple filters | eloquente - laravel

I would like to know if I am doing it right, if my code is semantic and safe.
I need to load a page from the database, but to do this I need to cross some data and all must be compatible, the verification takes place as follows:
url: mysite.com/company/page/code
1 - Check the first parameter to see if company exists or not.
2 - check the second parameter to find out if company X has that page or not
3 - Check the third parameter to find out if page Y has a code and if that code matches what you typed.
4 - If the user arrived here and all the data are correct, please load the page and the corresponding data.
Here he checks if user X has page Y, my doubt is if I can do it like this or is there another way.
$page = Page::where('name', $name)->where('page_name', $page_name)->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
Here is similar to the other, he checks if user X has page Y and if the code of page Y is correct, as in others, my doubt is if it is correct to put several WHERE clauses in the code
$pagecode = Page::where('name', $name)->where('page_name', $pagen_name)->where('code', $pcode)->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
as I thought you would want the code in general context, here is the full function code
public function loadpage($name, $page_name, $pcode)
{
$company = Company::where('name', $name)->first();
if ($company === null) {
return view('company.not_register', compact('name'));
}
$page = Page::where('name', $name)->where('page_name', $page_name)->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
$pagecode = Page::where('name', $name)->where('page_name', $page_name)->where('code', $pcode)->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
$personality = DB::table('personalities')->where('name', $name)->first();
return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode));
}
based on laravel's documentation, I came up with the following result:
public function loadpage($name, $page_name, $pcode)
{
$company = Company::where('name', $name)->first();
if ($company === null) {
return view('company.not_register', compact('name'));
}
$page = Page::where([ ['name', $name],
['page_name', $page_name],])->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
$pagecode = Page::where([ ['name', $name],
['page_name', $page_name], ['code', $pcode],])->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
$personality = DB::table('personalities')->where('name', $name)->first();
return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode));
}
now it's up to colleagues more experienced than me to see if that's right or is it possible to improve / simplify
In case you are searching in a single model and you are not sure when which fields occur you might want to use laravel's when() method. It will help you search the database only when the field is available for you. for an example:
$sortBy = null;
$users = DB::table('users')
->when($sortBy, function ($query, $sortBy) {
return $query->orderBy($sortBy);
}, function ($query) {
return $query->orderBy('name');
})
->get();
You will get the idea from here conditional query in laravel
if you have multiple where clause to pass to a where clause, you can have a array containing arrays with the structure as you would have in the where method, like:
$where = [
['name', $name],
['page_name', $page_name],
['code', $pcode],
/*
the arrays should have one of this two structure
["field", "value"], //using = operator as default
["field", "operator", "value"],
*/
];
and than call ->where() with this array as parameter, like:
Page::where($where)->first();
So your code can become
public function loadpage($name, $page_name, $pcode)
{
$name = ['name', $name];
$pageName = ['page_name', $page_name];
$pageCode = [ 'code', $pcode ];
$company = Company::where([$name])->first();
if ($company === null) {
return view('company.not_register', compact('name'));
}
$page = Page::where([$name, $pageName])->first();
if ($page === null) {
return view('company.pages.erros.404', compact('name', page));
}
$pagecode = Page::where([$name, $pageName, $pageCode])->first();
if ($pagecode === null) {
return view('company.pages.erros.invalid_code', compact('company, name', page, pcode));
}
$personality = DB::table('personalities')->where([$name])->first();
return view('company.pages.index', compact('company', 'name', 'personality', 'page', pcode));
}

Data not insert into codeigniter

I will try to insert & also update data using session in Codeigniter, but data not inserted into the database even its print save successfully.
Here is my controller:
public function save($user_id)
{
$this->load->model('Users');
$code=$this->input->post('code');
$name=$this->input->post('name');
$address=$this->input->post('address');
$user_data= array(
'code' =>$code,
'name'=>$name,
'address'=>$address,
'active'=>1
);
if($this->Users->save($user_data,$user_id))
{
$this->session->set_flashdata('msg',"save sucesss");
}else {
$this->session->set_flashdata('msg',"not save");
}
redirect('home');
}
& this is my model:
public function save($data,$id)
{
if (id=='') {
// code...
$this->db->insert('user',$data);
return true;
}else
{
$this->db->where('id',$id)
->update('user',$data);
return true;
}
return false;
}
Data insert if I removed if in model!
You have the model always returning true no matter the outcome of the database operation. You should use the return value from insert() or update() so the "message" reports what actually happens.
Note that the argument to save has a default value. Now you can call the save URL without an argument and it will automatically do an insert.
public function save($user_id = NULL)
{
$this->load->model('users');
$user_data = array(
'code' => $this->input->post('code'),
'name' => $this->input->post('name'),
'address' => $this->input->post('address'),
'active' => 1
);
if($this->Users->save($user_data, $user_id))
{
$msg = "save sucesss";
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
redirect('home');
}
public function save($data, $id)
{
if(empty($id))
{
// code...
// insert returns TRUE on success, FALSE on failure
return $this->db->insert('user', $data);
}
// update() accepts a third argument, a "where" array
// and returns TRUE on success, FALSE on failure
return $this->db->update('user', $data, array('id' => $id));
}
Now have an accurate report on the database operations.
the first check is data is coming in save controller or not if it's not getting the data then fix it. If coming then pass it in a model in the correct format and it will definitely be inserted in the database.
use following printing data
echo $data;
var_dump($data);
print($data);
print_r($data);
First thing is to rename your model calling eg:
$this->load->model('users');
and use this to call your method:
$this->users->save($user_data,$user_id)
your model should look like this then:
public function save($data, $id) {
if ($id) {
$this->db->where('id', $id)
->update('user', $data);
return true;
}
$this->db->insert('user', $data);
return true;
}
if you want to use your flashdata on the next request, use this:
$this->session->keep_flashdata('item');
$this->session->keep_flashdata(array('item1', 'item2', 'item3'));
because flashdata is only for the next request:
CodeIgniter supports “flashdata”, or session data that will only be available for the next request, and is then automatically cleared.

Laravel checking submitted values with database before update

Ive been trying to check the fields that a user submitted from the form with the database fields to see if there was any change made
if it was let the save() query run, else send a message that no changes made
public function update(Request $request,$id)
{
$this->validate($request, [
'title' =>'required',
'notes' =>'required',
'description' =>'required'
]);
$editinc = Editted::find($id);
if($editinc > 0) {
dd($editinc);
}
$data = $request->all();
$post= Joborder::find($id);
//before this query runs i want to check my fields with db
//if no changes has been this should not be executes
$post->fill($request->input())->save();
return redirect('/thehood')->with('success','WE DID IT.');
}
Additional Info :
im a newbie in Laravel so take it easy on me.
if isDirty() is possible , how ? I checked lots of questions still have no clue how to use it.
if its not possible then is there a Laravel way? something that checks and if there are difference it will ONLY change their value NOT perform a full update on every field.
Edited :
this could be a way but I'm pretty sure there is Laravel way that I just don't know about it??!
$post= Joborder::find($id);
$data = $request->all();
foreach($data as $dat => $val) {
if($dat=="_token" || $dat=="_method") continue;
if($data[$dat] == $post->$dat) {
continue;
}else{
$post->$dat = $data[$dat];
$post->save();
$flag=1;
}
}
if($flag == 0 ) {
return redirect('/thehood')->with('success','NO EDIT HAS BEEN DoNE.');
}else{
return redirect('/thehood')->with('success','one or more Field has been edited .');
}
Here is what you can do, please enter all the fields you want to compare in the query as I am not entering all of them.
$exist = Joborder::where('title', $request->input('title'))->where('notes', $request->input('notes'))->first();
if($exist)
{
//Insert into database.
}

capture user id when login and save user id based on operations

I need to capture login user and when i add question i need to save the corresponding user id in the questions table.i'm getting user id when i login but it is not saving in the question table
Controller with store function
public function store(Request $request)
{
//
$last_que = Question::orderBy('question_id', 'desc')->first();
if ($last_que != null) {
$old_queId = $last_que->question_id;
$old_queId = $old_queId + 1;
} else {
$old_queId = 1;
}
$qorder=$request->input('order');
$question=new Question();
$quest=$question->checkDuo($qorder);
if(count($quest)==0)
{
$que=Question::create([
'question'=>$request->input('question'),
'question_id'=>$old_queId,
'question_type'=>$request->input('qtype'),
'question_schedul'=>$request->input('qschedule'),
'created_user_id'=>Session::get('created_id'),
'order_no'=>$request->input('order')
]);
if($que)
{
return redirect()->route('questions.index')->with('success', 'Successfully saved');
}
}
else
{
return redirect()->back()->with('fail', 'Unable to save..! Entry with same order no. already exist');
}
}
in Login index file this is i used capture the user id
<?php
if (!empty($id)) {
Session::put('created_id', $id);
}
?>
Login controller
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user = DB::table('users')->where([['username', '=', $request['username']], ['status', '=', '0']])->first();
$user_id = $user->user_id;
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Get user ID. use something like this.
Auth:user()->id;
Or you can use
Session::getId();
Change this line,
'created_user_id'=>Session::get('created_id'),
To,
'created_user_id'=>Auth::id(),
You used $user_id
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
Than asking:
if (!empty($id)) {
This $id will be always empty so use:
<?php
if (!empty($user_id)) {
Session::put('created_id', $user_id);
}
?>

Laravel Checking If a Record Exists

I am new to Laravel. How do I find if a record exists?
$user = User::where('email', '=', Input::get('email'));
What can I do here to see if $user has a record?
It depends if you want to work with the user afterwards or only check if one exists.
If you want to use the user object if it exists:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
And if you only want to check
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
Or even nicer
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
if (User::where('email', Input::get('email'))->exists()) {
// exists
}
In laravel eloquent, has default exists() method, refer followed example.
if (User::where('id', $user_id )->exists()) {
// your code...
}
One of the best solution is to use the firstOrNew or firstOrCreate method. The documentation has more details on both.
if($user->isEmpty()){
// has no records
}
Eloquent uses collections.
See the following link: https://laravel.com/docs/5.4/eloquent-collections
Laravel 5.6.26v
to find the existing record through primary key ( email or id )
$user = DB::table('users')->where('email',$email)->first();
then
if(!$user){
//user is not found
}
if($user){
// user found
}
include " use DB " and table name user become plural using the above query like user to users
if (User::where('email', 'user#email.com')->first()) {
// It exists
} else {
// It does not exist
}
Use first(), not count() if you only need to check for existence.
first() is faster because it checks for a single match whereas count() counts all matches.
It is a bit late but it might help someone who is trying to use User::find()->exists() for record existence as Laravel shows different behavior for find() and where() methods. Considering email as your primary key let's examine the situation.
$result = User::find($email)->exists();
If a user record with that email exists then it will return true. However the confusing thing is that if no user with that email exists then it will throw an error. i.e
Call to a member function exists() on null.
But the case is different for where() thing.
$result = User::where("email", $email)->exists();
The above clause will give true if record exists and false if record doesn't exists. So always try to use where() for record existence and not find() to avoid NULL error.
This will check if requested email exist in the user table:
if (User::where('email', $request->email)->exists()) {
//email exists in user table
}
In your Controller
$this->validate($request, [
'email' => 'required|unique:user|email',
]);
In your View - Display Already Exist Message
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Checking for null within if statement prevents Laravel from returning 404 immediately after the query is over.
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
would work with try/catch
->get() would still return an empty array
$email = User::find($request->email);
If($email->count()>0)
<h1>Email exist, please make new email address</h1>
endif
Simple, comfortable and understandable with Validator
class CustomerController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:customers',
'phone' => 'required|string|max:255|unique:customers',
'password' => 'required|string|min:6|confirmed',
]);
if ($validator->fails()) {
return response(['errors' => $validator->errors()->all()], 422);
}
I solved this, using empty() function:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
you have seen plenty of solution, but magical checking syntax can be like,
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
it will automatically raise an exception with response 404, when not found any related models Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The fingernail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, an Illuminate\Database\Eloquent\ModelNotFoundException will be thrown.
Ref: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
This will check if particular email address exist in the table:
if (isset(User::where('email', Input::get('email'))->value('email')))
{
// Input::get('email') exist in the table
}
Shortest working options:
// if you need to do something with the user
if ($user = User::whereEmail(Input::get('email'))->first()) {
// ...
}
// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
can be written as
if (User::where('email', '=', Input::get('email'))->first() === null) {
// user doesn't exist
}
This will return true or false without assigning a temporary variable if that is all you are using $user for in the original statement.
I think below way is the simplest way to achieving same :
$user = User::where('email', '=', $request->input('email'))->first();
if ($user) {
// user exist!
}else{
// user does not exist
}
Created below method (for myself) to check if the given record id exists on Db table or not.
private function isModelRecordExist($model, $recordId)
{
if (!$recordId) return false;
$count = $model->where(['id' => $recordId])->count();
return $count ? true : false;
}
// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);
Home It helps!
The Easiest Way to do
public function update(Request $request, $id)
{
$coupon = Coupon::where('name','=',$request->name)->first();
if($coupon->id != $id){
$validatedData = $request->validate([
'discount' => 'required',
'name' => 'required|unique:coupons|max:255',
]);
}
$requestData = $request->all();
$coupon = Coupon::findOrFail($id);
$coupon->update($requestData);
return redirect('admin/coupons')->with('flash_message', 'Coupon updated!');
}
Laravel 6 or on the top: Write the table name, then give where clause condition for instance where('id', $request->id)
public function store(Request $request)
{
$target = DB:: table('categories')
->where('title', $request->name)
->get()->first();
if ($target === null) { // do what ever you need to do
$cat = new Category();
$cat->title = $request->input('name');
$cat->parent_id = $request->input('parent_id');
$cat->user_id=auth()->user()->id;
$cat->save();
return redirect(route('cats.app'))->with('success', 'App created successfully.');
}else{ // match found
return redirect(route('cats.app'))->with('error', 'App already exists.');
}
}
If you want to insert a record in the database if a record with the same email not exists then you can do as follows:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
The updateOrCreate method's first argument lists the column(s) that uniquely identify records within the associated table while the second argument consists of the values to insert or update.
You can check out the docs here: Laravel upserts doc
You can use laravel validation if you want to insert a unique record:
$validated = $request->validate([
'title' => 'required|unique:usersTable,emailAddress|max:255',
]);
But also you can use these ways:
1:
if (User::where('email', $request->email)->exists())
{
// object exists
} else {
// object not found
}
2:
$user = User::where('email', $request->email)->first();
if ($user)
{
// object exists
} else {
// object not found
}
3:
$user = User::where('email', $request->email)->first();
if ($user->isNotEmpty())
{
// object exists
} else {
// object not found
}
4:
$user = User::where('email', $request->email)->firstOrCreate([
'email' => 'email'
],$request->all());
$userCnt = User::where("id",1)->count();
if( $userCnt ==0 ){
//////////record not exists
}else{
//////////record exists
}
Note :: Where condition according your requirements.
Simply use this one to get true or false
$user = User::where('email', '=', Input::get('email'))->exists();
if you want $user with result you can use this one,
$user = User::where('email', '=', Input::get('email'))->get();
and check result like this,
if(count($user)>0){}
Other wise you can use like this one,
$user = User::where('email', '=', Input::get('email'));
if($user->exists()){
$user = $user->get();
}
The efficient way to check if the record exists you must use is_null method to check against the query.
The code below might be helpful:
$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
//user does not exist...
}else{
//user exists...
}
It's simple to get to know if there are any records or not
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";

Categories