I am trying to use AND as well as && in this code block:
public function show($id)
{
$user = Auth::user()->id;
$userEmail = Auth::user()->email;
$share = Share::where('sbj_id', $id)->first();
if ($share->sbj_id == $id && $share->email == $userEmail ) {
$items = Item::where('project_id', $id)
->orderBy("created_at", "desc")
->groupBy('label_name')
->get();
$sbj = Sbj::find($id);
$allSbj = Sbj::where('user_id', $user)->orderBy("created_at", "desc")->get();
$labels = Label::all();
$pages = Page::where('project_id', $id)->orderBy('created_at', 'desc')->get();
$people = Friend::where('sbj_id', $id)->orderBy("created_at", "desc")->get();
$myPeeps = Contact::where('my_id', $user)->get();
return View::make('sbjs.show', compact('sbj', 'pages', 'labels', 'people', 'myPeeps', 'allSbj', 'items'));
} else {
return Redirect::action ('SbjsController#index');
}
}
However, I am looking online to see if && or AND is supported in Lavavel in this context but no success. My app is taking the user to the ELSE action.
Any ideas?
I just added the Eloquent statement to the IF conditional and it worked fine...not sure why it was not evaluating.
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
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
public function returnsTrueIfEmailIsVerified(Request $request)
{
// Gets the email
$email = request("email"); //johndoe#example.com for example
// Determine if zero or one ;
$user = User::where('email','=',$email)->get(); // 0 or 1 ;
$userCount = User::where('email','=',$email)->count(); // 0 or 1 ;
$confirmedValue = $user->get('confirmed');
$response ;
if ( $user === 1 && $confirmedValue === true ) {
$response = 'OK';
}
elseif ($user === 1 && $confirmedValue === false) {
$response = 'Not Confirmed yet';
}
else {
$response = 'Not Registered yet';
}
return response()->json(200,$response);
}
with that code I would return a response that if a user isn't registered or is registered and that if he's registered but that he's not confirmed yet..
I want to return something out from that I'm not just familiar with laravel's way
There are so many error in your code, I've fixed it and this code will work. I think you need to learn more Laravel and PHP.
public function returnsTrueIfEmailIsVerified(Request $request)
{
$email = request("email");
$user = User::where('email', '=', $email);
$response = [
'message' => ''
];
if ($user->count() === 1) {
$confirmedValue = $user->first()->confirmed;
if ($confirmedValue) {
$response['message'] = 'OK';
} else {
$response['message'] = 'Not Confirmed yet';
}
} else {
$response['message'] = 'Not Registered yet';
}
return response()->json($response, 200);
}
you can't response string as a json, json is key value pair.
User::where('email', '=', $email) return Query Builder not 0 or 1, use count() method;
you can't retrieve value from multiple items you have to specific item like this $user->get()[0]['confirmed] or use Laravel special method $user->first()->confirmed
I'm building a filter function in a project.
I have a filter option "Show newest", "Show oldest" and a bunch of other options. I found a way how to implement conditional where clauses, but there doesn't seems to be a conditional orderBy class.
My conditional where clause looks like this:
$query->where(function($query) use ($request){
if( ! empty($request->input('prices')) ){
$opts = $request->prices;
$query->where('price_id', $opts[0]);
}
})
Is there a way to do this with a ->orderBy too?
UPDATE
return Auction::where('end_date', '>', Carbon::now() )
->where('locale', $locale)
->where('sold', 0)
->where(function($query) use ($request){
if( ! empty($request->input('prices')) ){
$opts = $request->prices;
$query->where('price_id', $opts[0]);
}
})->paginate(8);
How can I do it in the eloquent-way?
Of course, you can do it this way:
if ($request->input('id_desc')) {
$query = $query->orderBy('id', 'DESC');
}
or you can do it this way:
$columns = ['id','name',]; // here define columns you allow for sorting
$orderBy = ['ASC', DESC'];
$column = $request->input('order_by_column');
$type = $request->input('order_by_type');
if (!in_array($column, $columns)) {
$column = 'id';
}
if (!in_array($type , $orderBy )) {
$type = 'ASC';
}
$query = $query->orderBy($column, $type);
EDIT
Using your code:
$query = Auction::where('end_date', '>', Carbon::now() )
->where('locale', $locale)
->where('sold', 0)
->where(function($query) use ($request){
if( ! empty($request->input('prices')) ){
$opts = $request->prices;
$query->where('price_id', $opts[0]);
}
});
if ($request->input('id_desc')) {
$query = $query->orderBy('id', 'DESC');
}
return $query->paginate(8);
I am calling URL with search params which are dynamic. How could I form proper Eloquent query?
In theory:
query
query where(someParam1)
query where(someParam2)
query orderby(someParam3)
query get
I need this kind of structure so I can use where clause if param exists.
If there is some other way in Laravel, please let me know.
It's easy with Laravel. Just do something like this:
$query = User::query();
if ($this == $that) {
$query = $query->where('this', 'that');
}
if ($this == $another_thing) {
$query = $query->where('this', 'another_thing');
}
if ($this == $yet_another_thing) {
$query = $query->orderBy('this');
}
$results = $query->get();
You can just use the where statement.
For ex: on users table or User model, you want dynamic search on name, id. You can do this
$where = [];
$firstName = $request->get('first_name');
if ($firstName) $where[] = ['first_name', 'like'. '%' . $firstName . '%'];
$id = $request->get('id');
if ($id) $where[] = ['id', $id];
$users = User::where($where)->get();
By default, it will return all the users, if anything exists in $where array, it will apply the where condition on that.
You can use like this
$validateUserDetail = User::query();
if (!empty($userDetails['email'])) {
$validateUserDetail->whereemail($userDetails['email']);
}if (!empty($userDetails['cellphone'])) {
$validateUserDetail->wherecellphone($userDetails['cellphone']);
}
$validateUserDetail->select('username');
$validateUserDetail->get()
You can pass dynamic value by below example
$user_auctions = $this->with('userAuctions')
->where('users.id', '=', $id)
->get();
I came here from Google. If you are going to be iterating over more then 5 if statements, its more effective to use a switch statement
if(empty($request->except('_token')))
return 'false';
$models = Vehicle::query();
$request_query = $request->all();
$year_switch = false;
foreach ($request_query as $key => $field_value){
if($field_value != 'any'){
switch($field_value){
case 'X':
case 'Y':
$year_switch = true;
break;
case'Z':
//Dynamic
$models->where($key,'LIKE', $field_value);
break;
}
}
}
You can pass a callback to the where function.
So, you can do something like this:
class TestService {
TestRepository $testeRepository;
public function __construct(TesteRepository $teste) {
$this->testeRepository = $teste;
}
public function getAll(array $filters)
{
$where = function (Builder $query) use ($filters) {
collect($filters)
->each(function ($value, $param) use ($query) {
if ($param === 'test') {
$query->where($param, '=', $value);
} else if ($param === 'test2') {
$query->orWhere($param, '>', $value);
}
});
};
return $this->testRepository->gelAll($where);
}
class TestRepository
{
public function getAll(\Closure $where)
{
$query = TestModel::query();
$query->where($where);
//and put more stuff here, like:
//$query->limit(15)->offset(30)
...
return $query->get();
}
}
And in your controller you pass the filters:
class TestControler ...
{
public function $index()
{
$filters = request()->query();
return $this->testService->getAll($filters);
}
}