put single row to variable and delete it at same time with one query - laravel

I have a password_resets table in mysql database and i want to get single raw of data and delete it with one query in Lumen with DB facade like this:
$reset_row = DB::table('password_resets')->where('token', $request->token)->first()->delete();
But i have a error :
Call to undefined method stdClass::delete()
i try this code :
$reset_row = DB::table('password_resets')->where('token', $request->token)
//do my work whith $reset_row->first();
$reset_row->delete();
But i think this way use 2 query to do this work.
NOTE : i know i can not delete and reason is first() method )return it to array)
Is there any way to do this?

Actually no need to use ->first(). Bcz your token is unique.
if you need try this.
$reset_row = DB::table('password_resets')->where('token', $request->token)
->Limit(1)->delete();
I think it is possible to use "limit" with "delete".

You can simply chain the delete method to your Query Buider.
No need to select the first on since you want to delete them, not select them.
DB::table('password_resets')->where('token', $request->token)->delete();
Its already answered in another post in StackOverflow.
You can use this answer too
laravel-delete-query-builder and you can also look at the official documentation about deleting using the query builder

At the end I Think to create model for reset password and Use it like this:
1. set primary key to token by set it on model like this
2. use find method to find token (document for find method)
use this way:
$reset=PasswordReset::find($token);
//work with $reset
$reset->delete()
NOTE: : for set primary key to string col see this link too

Related

How to use something else than "find" in the #can directive when looking for a specific model instance?

I have this policy file used for SomeModel
class SomeModelPolicy{
...
public function delete($user, SomeModel $someModel){
return $user->can('update', $someModel->someOtherBelongsToModel)
}
}
and want to use a #can directive in order to specify who should be able to delete a model via a graph ql query.
Normally, i would write something like this
#can(ability: "delete" find:id model:"App\\Models\\SomeModel")
but this specific graphql query is not selecting by id (which is primary key) but by other key called public_id.
Now, i've read in the documentation that i should use something like
#can(ability: "delete" query:true model:"App\\Models\\SomeModel")
in combination with "directives that add constraints to the query builder, such as #eq", as the docs specify, but i can make literally nothing work with the query
i've tried
#eq(key: "public_id" value:public_id)
or
#where(key:"public_id" operator:"=")
but graphql just always throws error saying
`Too few arguments to function App\\Policies\\SomeModelPolicy::delete(), 1 passed `
I have been pulling my hair for hours. The docs are really unhelpful, there are almost no examples online and the Lighthouse's error message is not helpful at all, providing a vague message with an irrelevant stack trace.

I want to check duplication value during insert time without using unique keyword

i make one table for with some column with nullable.
i already tried with two different query. one using
Register_member::where('passport',$passport)->orWhere('adharcardnumber',$adharcardnumber)->get();
and second DB::table type query.
$row = Register_member::where('passport',$passport)->orWhere('adharcardnumber',$adharcardnumber)->get();
if (!empty($row))
{
return response()->json(["status"=>0, "message"=>"Adharcard or Paasport number already exit."]);
}
if (empty($row))
{
Register_member::insert(['first_name'=>request('first_name'), 'middle_name'=>request('middle_name'), 'last_name'=>request('last_name'), 'adharcardnumber'=>request('adharcardnumber'), 'ocipcinumber'=>request('ocipcinumber'), 'passport'=>request('passport'), 'birthday'=>request('birthday'),
'mobilecode'=>request('mobilecode'), 'mobilenumber'=>request('mobilenumber'), 'email'=>request('email'), 'address'=>request('address'), 'landmark'=>request('landmark'), 'area'=>request('area'),
'gender'=>request('gender'), 'pincode'=>request('pincode'), 'city_name'=>request('city_name'), 'state_id'=>request('state_id'), 'country_id'=>request('country_id'), 'sampraday'=>request('sampraday'), 'other'=>request('other'), 'sms'=>request('sms')]);
return response()->json(["status"=>1, "message"=>"Member register successful."]);
}
if adharcardnumber or passport number are exists in table, then nagetive response. if in both any one in unique then, insert data in table
Let me suggest you something which I think serve you as a good solution. You can use the unique with required and regex. In this way it will use the already recommended ways of Laravel which are the best.
As an example for your adhaar card,
the validation should look like this
$request->validate([
'adhaar ' =>['required','unique:users','regex:/\d{12}/'],
]);
where adhar is the filed name where adhaar number is entered. Be sure to use validator like this use Illuminate\Support\Facades\Validator;. Also $request is the instance of the Request.
Using the required prevent empty field submission and the regex will throw an error if the pattern is not matched completely. so I think it would be a better a way to handle the scenario.
the above solution will work in both adhaar and passport. But for the passport the regex will be different though.
Please note these are all demo examples, you might need to modify it according to your needs. I use https://www.phpliveregex.com/ for regex making and checking and it is good enough.
I hope you get an idea of how to begin but if you need more information then let me know in the comments.

How to do string functions on a db table column?

I am trying to do string replace on entries of a column inside a db table. So far, I have reached till here:
$misa = DB::table('mis')->pluck('name');
for($i=0;;$i++)
{
$misa[$i] = substr_replace("$misa[$i]","",-3);
}
The error I am getting is "Undefined offset:443".
P.S. I am not a full-fledged programmer. Only trying to develop a few simple programs for my business. Thank You.
Since it's a collection, use the transform() collection method transform it and avoid this kind of errors. Also, you can just use str_before() method to transform each string:
$misa = DB::table('mis')->pluck('name');
$misa->transform(function($i) {
return str_before($i, ':ut');
});
There are a few ways to make this query prettier and FASTER! The beauty of Laravel is that we have the use of both Eloquent for pretty queries and then Collections to manage the data in a user friendly way. So, first lets clean up the query. You can instead use a DB::Raw select and do all of the string replacing in the query itself like so:
$misa = DB::table('mis')->select(DB::raw("REPLACE(name, ':ut' , '') as name"));
Now, we have a collection containing only the name column, and you've removed ':ut' in your specific case and simply replaced it with an empty string all within the MySQL query itself.
Surprise! That's it. No further php manipulation is required making this process much faster (will be noticeable in large data sets - trust me).
Cheers!

Displaying Data from an Eloquent collection with Relations

I'm trying to get data from an Eloquent query as follows:
$submission->find($id)->first()->with('user', 'clientform')->get();
I'm sending the submission to the view and attempting to access properties from the user model like so:
{{ $submission->clientform->name }}
However, Laravel is throwing the following error:
Undefined property: Illuminate\Database\Eloquent\Collection::$clientform
What am I doing wrong with the way my query is formatted?
You're overdoing it!
Let's break it down:
$submission->find($id);
Will return an instance of the model which corresponds to the entry having the primary key of $id.
$submission->find($id)->first();
This is an unncessary repetition; the find method already gives you a single entry, no need to call first on it.
$submission->find($id)->first()->with('user', 'clientform');
This is where you start going the wrong way; when calling with on a model, Laravel will transform that model into a query builder again, even though it was already resolved by calling find.
$submission->find($id)->first()->with('user', 'clientform')->get();
Finally, the get method resolves the builder into a Illuminate\Support\Collection, regardless of the number of entries found (i.e. it could be a Collection of only one item). It's worth noting, though, that your query will most likely have been fully reset by calling with. It would be the same as instantiating a fresh Submission model and building your query with it. That means you're probably using a collection of all your submission entries, not just the one with $id.
Long story short, this is what you want:
$submission->with('user', 'clientform')->find($id);
It will fetch the matching $id, with the user and clientform relations eager-loaded.

Propel having() with criteria

I add a virtual column, then I filter it using "having". When I need to filter by one value, all works fine, but I also need to filter by "not null". having expects only 3 arguments, including the clause, the value and the binding type, is there any way to pass in a criteria?
$Sharings->having("TotalSharing = ?",2, \PDO::PARAM_INT);
Or do I have to add a new virtual column who has as value what I need directly?
Thanks a lot in advance!
Gioia
Ok, was actually a lot easier then I thought, I just used:
$Sharings->having("TotalSharing > ?",0, \PDO::PARAM_INT);
So I didn't need to use a Criteria object, silly of me not to think about this, just so used to use filterBy...

Resources