Laravel 5.5 where condition - laravel

I have problem in searching, I am using Laravel 5.5 version, the situation like this: I have groups which study during some period of time. On filtering page, Admin enters study starting date and ending date, the result must show all groups which studied or studying between given time period. A comparing in simple way is not working, I would like to use strtotime function, but when I use:
->where(strtotime('edu_ending_date'),'=<',strtotime($edu_ending_date));
the eloquent is saying there is not such a column name ...
if(!empty($input['daterange']))
{
$q->where(function($query)use($edu_starting_date,$edu_ending_date){
$query->where('edu_starting_date', '>=', "$edu_starting_date")
->where('edu_ending_date','=<',"$edu_ending_date");
});
}

if you need to use dates in your where clauses I might want to have a look at this article and this section of laravel docs where they mention additional where clauses which include also whereDate, whereDay, etc. Might come in handy. In your case I would suggest you to do two whereDate conditions to act as between:
$query->whereDate('edu_starting_date', '>=', $edu_starting_date)
->whereDate('edu_ending_date', '=<', $edu_ending_date)
Note that $edu_starting_date and $edu_ending_date are recommended to be a Carbon object or output of PHP's date function. If you want to use strings according to the Laravel docs it should be possible. Hopefully this helps you :)

You can use
$q->whereBetween('edu_starting_date', [$edu_starting_date,$edu_ending_date])

try this:
if(!empty($input['daterange']))
{
$q->where(function($query)use($edu_starting_date,$edu_ending_date){
$query->where('edu_starting_date', '>=', $edu_starting_date)
->where('edu_ending_date','=<',$edu_ending_date);
});
}

The date is saved as a string in my database, is that ok, that is why I would like to use
something like this:
->where(strtotime('edu_ending_date'),'=<',strtotime($edu_ending_date));

You can use DB::raw
->where(DB::raw("strtotime('edu_ending_date')"),'=<',strtotime($edu_ending_date));

Thank you guys, I found my stupid mistake, I stored date as a string.

Related

Laravel query builder raw case

I am trying to use a case control structure in a Laravel.I can not for the life of me get the required 'blueberry' result even though there are muffins with the 'App\Models\blueberrymuffin' type in the database.
$muffintype=DB::table('muffins')
->select(
DB::raw"(CASE muffin_type WHEN 'App\Models\blueberrymuffin' THEN 'Blueberry' END)" ))->get();
I don't think it is my syntax since when I test this out it works.
$muffintype=DB::table('muffins')
->select(
DB::raw"(CASE milk_type WHEN 'coconut' THEN 'Vegan' END)" ))->get();
I am thinking it has something to do with the ""in the muffin type. The muffin_type is a varchar(255). Does anyone have a clue because I am very perplexed. Thank you in advance
If a string contains forward slashes, those should be escaped:
DB::raw("(CASE muffin_type WHEN 'App\\Models\\blueberrymuffin' THEN 'Blueberry' END)")
Pls also have a look at this thread.

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!

How to do to get the last insert of below laravel code?

How to do to get the last insert of below laravel code?
$v_videos = VCategory::find($id)->videos->toArray();
Can anyone help? Thanks.
I use the reverse() method and fixed it.
VCategory::find($id)->videos->reverse()->toArray();
Thanks you.
If you're using timestamps for your models you can do this:
VCategory::find($id)->videos()->orderBy('created_at', 'desc')->first();
Otherwise you can still use the id (given its auto-increment)
VCategory::find($id)->videos()->orderBy('id', 'desc')->first();
Edit
There's also a little shortcut for the orderBy part.
VCategory::find($id)->videos()->latest()->first();
Or
without timestamps:
VCategory::find($id)->videos()->latest('id')->first();
Thanks #Joseph Silber for `latest()`

How to massive delete in php-activerecord where id NOT in list?

I'm running a CodeIgniter application with PHP-Activerecord installed and I need to do a massive delete. The PHP-AR library supports massive update and delete, but the function only takes the ids that you want to delete/update. I'm trying to do a massive delete where the ids are NOT in the list.
delete from table where id not in (1,2,3...,500)
Unfortunately, the PHP-Activerecord website is of no help, and their forums are so horribly built (no search... seriously?) that I'm truly stuck.
edit: Please note, CodeIgniter's built-in ORM is not the same as PHP-Activerecord. Just thought I'd clarify that.
A bit late but this may help someone else. In PHPActiveRecord, do it in this way:
$ids_to_delete = array(1,2,3);
YourModel::delete_all(array('conditions' => array('id NOT IN (?)', $ids_to_delete)));
Ref: http://www.phpactiverecord.org/docs/ActiveRecord/Model#methoddelete_all
SInce active record is actually build string query with function, you can use this method:
- make your list as string
- make this query : $this->db->where('id not in',$string)->delete('table')

Resources