I use Laravel in a basic wamp server
I've got the error Value must be provided.
this is the controller code :
public function edit($id)
{
$query = DB::table('submenus');
$content = Content::find($id);
$galleries = Gallery::where('parent_id', '<>', $content->parent_id)->lists('parent_id', 'id');
$contents = Content::where('parent_id', '<>', $content->parent_id)->lists('parent_id', 'id');
$this_parent = Submenu::where('id' , '=' , $content->parent_id)->first();
/*if (!empty($galleries))
{
$query->whereNotIn('id', $galleries);
}
if (!empty($contents))
{
$query->whereNotIn('id', $contents);
}*/
$submenus = $query->lists('name', 'id');
asort($submenus);
$submenus[null] = "Aucun";
$this->layout->content = View::make('contents.edit', array(
"content" => $content,
"submenus" => $submenus,
"contents" => $contents,
"galleries" => $galleries
));
}
And the error message :
InvalidArgumentException
Value must be provided.
From: C:\webroot\okalli\rest\vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php
// and keep going. Otherwise, we'll require the operator to be passed in.
if (func_num_args() == 2)
{
list($value, $operator) = array($operator, '=');
}
elseif ($this->invalidOperatorAndValue($operator, $value))
{
throw new \InvalidArgumentException("Value must be provided.");
}
I really don't know what is the problem..
It seems that $content->parent_id is null for the record you find and when you use <> operator it will throw this exception (null is allowed only for = operator).
Make sure you get from database what expect and you have parent_id column filled properly.
Quick solution would be using ternary operator:
$galleries = Gallery::where('parent_id', '<>', ($content->parent_id) ?: 0 )->lists('parent_id', 'id');
$contents = Content::where('parent_id', '<>', ($content->parent_id) ?: 0 )->lists('parent_id', 'id');
instead of
$galleries = Gallery::where('parent_id', '<>', $content->parent_id)->lists('parent_id', 'id');
$contents = Content::where('parent_id', '<>', $content->parent_id)->lists('parent_id', 'id');
Related
i am a bit confused as i have tried what i understand about fetching an item in an array in an object .
let me break down
in my client endpoint
$client=Client::where('id',$client)->firstOrFail();
$arr = json_decode($client->attributes);
return response()->json($arr);
when i return like this
return response()->json($client->attributes);
i get
{
"full_details_acknowledgement": "10",
"offer_letter_acknowledgement": "10",
"offer_letter": "10",
"offer_letter_variables": [
"basic_salary",
"housing_allowance",
"transport_allowance",
"meal",
"entertainment",
"hazard_allowance",
"leave_allowance",
"utility",
"monthly_gross_salary",
"statutory_deductions",
"employee_pension",
"payee_tax",
"total_deductions",
"net_monthly_salary",
"austin"
],
"company": "global-manpower"
}
i am trying to get the values of offer_letter_variables and safe them in a variable
like this , this is also what i have tried
foreach ($client->attributes['offer_letters_variables'] as $variable){
$offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );
}
but if i try it as the above i have the error
"message": "Cannot access offset of type string on string"
heres a full view of my code(i commented out some parts)
public function submitSingleUploadCandidates($client,Request $request){
$request->validate([
'job_role_id'=>'required',
'mail_template_id'=>'required',
'first_name'=>'required',
'last_name'=>'required',
'user_type'=>'required',
'email'=>'required',
]);
$job_level=JobLevel::find($request->job_level_id);
$job_role=JobRole::findOrFail($request->job_role_id);
$mail_template=MailTemplate::findOrFail($request->mail_template_id);
$client=Client::where('id',$client)->firstOrFail();
//return response()->json($client->attributes);
// $arr = json_decode($client->attributes);
//dd($client);
// return response()->json(gettype($arr));
// return response()->json($arr);
$offer_letters_variables=collect([]);
//return response()->json($offer_letters_variables);
// $var = $client->attributes[''];
// dd($var);
foreach ($client->attributes['offer_letters_variables'] as $variable){
$offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );
}
$attr=collect(['offer_letter_variables'=>$offer_letters_variables]);
$user=User::where('email',$request->email)->first();
if ($user){
Session::flash('fail', 'Candidate with email already exist');
$payload=['status'=>'fail','details'=>'Candidate with email already exist'];
return response()->json($payload, 200);
return redirect()->back()->withInput();
}
$password=Str::random(7);
$job_level_id = $job_level->id ?? null;
$new_user=User::create([
'client_id'=>$client->id,
'email'=>$request->email,
'emp_num'=>$request->emp_num,
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'stage_id'=>1,
'user_type'=>$request->user_type,
'job_level_id'=>$job_level_id,
'job_role_id'=>$job_role->id,
'attributes'=>$attr,
'password'=>Hash::make($password),
]);
// $mail_constants['MacTay Signature Banner'] = '';
$mail_constants = $this->getMailConstants($new_user);
$mail_constants['candidate_password']=$password;
$mail_constants['deadline']=Carbon::now()->addWeekdays(2)->format('D d M, Y');
$mail_constants['admin_name']=auth()->user()->name;
$mail_content=$this->convertMailTemplateToEmail($mail_template,$mail_constants);
$mail_template->subject = str_replace('{{job_role}}', $mail_constants['job_role'], $mail_template->subject);
$mail_template->subject = str_replace('{{client_name}}', $mail_constants['client_name'], $mail_template->subject);
Mail::to($new_user->email)->send(new AdminSendMail($mail_content,$mail_template->subject));
$message="Your account has been created on Mactay App. Email: {$new_user->email}, Temp Password: {$password}. URL: onboarding.mactay.com";
SendSMSJob::dispatch($new_user->phone,$message);
activity()->withProperties(['client_id' => $client->id])->log('Upload single candidate to '.$client->name);
Session::flash('success', 'Successfully Uploaded Single Candidates Details');
$payload=['status'=>'success','details'=>'Successfully Uploaded Single Candidates Details'];
return response()->json($payload, 200);
}
please what am i doing wrong, please help , thanks in advance
You forgot to json_decode $client->attributes
$clientAttributes = json_decode($client->attributes);
foreach ($clientAttributes->offer_letter_variables as $variable){
$offer_letters_variables->put(
$variable,
$request->{$variable} ?? 'not set'
);
}
$attr = collect(['offer_letter_variables' => $offer_letters_variables]);
if you want to access it like an array you can json_decode the value like as an associative array.
$clientAttributes = json_decode($client->attributes, true);
dd($clientAttributes['offer_letter_variables']);
Also not that you have misspelled offer_letter_variables as offer_letters_variables in you foreach loop.
You will get offer_letter_variables like this.
$offerLetters = 0;
$client=Client::where('id',$client)->firstOrFail();
if(isset($client->attributes['offer_letter_variables'])){
$offerLetters = $client->attributes['offer_letter_variables'];
}
do you need to use the second parameter of json_decode ? For remember, used if it's an associative array
$client=Client::where('id',$client)->firstOrFail();
$arr = json_decode($client->attributes);
What return gettype() ? Array ?
thanks to #maazin , the solution was to use json_decode $client->attributes and then use foreach like so
$clientAttributes = json_decode($client->attributes);
foreach ($clientAttributes->offer_letter_variables as $variable){
$offer_letters_variables->put(
$variable,
$request->{$variable} ?? 'not set'
);
}
$attr = collect(['offer_letter_variables' => $offer_letters_variables]);
enter image description here
I have several inputs in order to filter products in the online shop. My question is, how can I filter products if some inputs are left without being filled/chosen. How should I query?
public function find()
{
$categories = Category::all();
if (isset($_GET['submit'])) {
if (!empty($_GET['brand'])) {
$selectedBrand = $_GET['brand'];
echo 'You have chosen: ' . $selectedBrand;
} else {
echo 'Please select the value.';
}
$date = Request::get('date');
$name = Request::get('name');
$selected = $_GET['type'];
$data = DB::table('product')->where('product.type', $_GET['type'])
->where('product.name', $name)
->join('shop', 'product.id', '=', 'shop.product_id')
->where('shop.releasedate', $date)
->get();
return view('pages/catalog')->with(['product' => $data, 'categories' => $categories]);
}
}
You can first check if your fields are filled and continue to query your model with when method
Logic
$date = null;
if($request->filled('date)){
$date = $request->date;
}
// your other values can go here like above
$data = DB::table('product')->where('product.type', $_GET['type'])
->where('product.name', $name)
->join('shop', 'product.id', '=', 'shop.product_id')
->when($date, function ($query, $transmission) {
// this query runs only if $date is `true` (has a value and not empty)
return return $query->where('shop.releasedate','=', $date);
->orderBy('shop.created_at','desc);
}, function ($query) {
// something you want to return if the $date is `false` (empty)
})
->get();
How can I concatenate queries using Eloquent Builder?
I am building queries based on criteria (where clause) and taking limit and offset from URL. These queries are then passed to ->get() method to fetch result. I want to do it using Eloquent and not Query builder.
This is how you build a query in eloquent(I have given an example of using multiple where clauses):
$result = ModelName::where('key_1', '=' , 'value_1')
->where('key_2', '>', 'value_2')
->take(4)
->offset(2)
->get()
The take() method will limit the number of results to 4 with offset 2.
http://laravel.com/docs/5.0/eloquent
Update
Based on OP's question over here https://laracasts.com/discuss/channels/general-discussion/eloquent-query-builder , I am updating my answer.
You could do something like this:
if($params)
{
$query = $this->model;
foreach($params['search'] as $param)
{
$query = $query->where($param['where'],'=',$param['value']);
}
if (isset($params['start']))
{
$query = $query->offset($params['start'] );
}
if(isset($params['count']))
{
$query = $query->take($params['count']);
}
if (isset($params['sortColumn']))
{
$ascending = $params['ascending'] == 'true' ? 'ASC' : 'DESC';
$query = $query->orderBy($params['sortColumn'], $ascending);
}
}
$query->get();
What you need is assigning result of functions again to the model.
You had:
if($params)
{
foreach($params['search'] as $param)
{
$this->model->where($param['where'],'=',$param['value']);
}
if (isset($params['start']))
{
$this->model->offset($params['start'] );
}
if(isset($params['count']))
{
$this->model->take($params['count']);
}
if (isset($params['sortColumn']))
{
$ascending = $params['ascending'] == 'true' ? 'ASC' : 'DESC';
$this->model->orderBy($params['sortColumn'], $ascending);
}
}
$this->model->get();
and you need to use:
if($params)
{
foreach($params['search'] as $param)
{
$this->model = $this->model->where($param['where'],'=',$param['value']);
}
if (isset($params['start']))
{
$this->model = $this->model->offset($params['start'] );
}
if(isset($params['count']))
{
$this->model = $this->model->take($params['count']);
}
if (isset($params['sortColumn']))
{
$ascending = $params['ascending'] == 'true' ? 'ASC' : 'DESC';
$this->model = $this->model->orderBy($params['sortColumn'], $ascending);
}
}
$data = $this->model->get();
I'm having a problem while running this code:
//DashboardController
public function getStream()
{
$user = Sentry::getUser();
$userid = $user->id;
$convs = TBMsg::getUserConversations($userid);
$getNumOfParticipants = $convs->getNumOfParticipants();
$participants = $convs->getAllParticipants();
$lastMessage = $convs->getLastMessage();
$senderId = $lastMessage->getSender();
$content = $lastMessage->getContent();
$status = $lastMessage->getStatus();
$posts = Post::whereIn('user_id', function($query) {
$query->select('follow_id')
->from('user_follows')
->where('user_id', '1');
})->orWhere('user_id', '1')->get();
return View::make('stream', array('getNumOfParticipants' => $getNumOfParticipants,
'participants' => $participants,
'lastMessage' => $lastMessage,
'senderId' => $senderId,
'content' => $content,
'status' => $status
))->with('posts', $posts)->with('convs', $convs);
}
}
I got this error: Call to undefined method Illuminate\Support\Collection::getNumOfParticipants()
http://i.stack.imgur.com/9N3xU.png
Replace ->get() with ->first() as right now you're basically returning an collection of arrays but you need that.
$query->select('follow_id')
->from('user_follows')
->where('user_id', '1');
})->orWhere('user_id', '1') // ->get() is removed
->first();
$convs is a collection so you can't call a method on it that only exists on a single model. Like the tutorial of the package suggests you have to iterate over the collection to use that function.
From the how to:
foreach ( $convs as $conv ) {
$getNumOfParticipants = $conv->getNumOfParticipants();
$participants = $conv->getAllParticipants();
/* $lastMessage Tzookb\TBMsg\Entities\Message */
$lastMessage = $conv->getLastMessage();
$senderId = $lastMessage->getSender();
$content = $lastMessage->getContent();
$status = $lastMessage->getStatus();
}
Is it possible to split queries somehow like this?
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query = $query->where('from', $dates['from']);
if ($dates['to'])
$query = $query->where('to', $dates['to']);
$query = $query->select('Active');
return $query->get()->toArray();
}
Yes, it's possibile. But don't reassign to the same variable or you risk messing it up:
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query->where('from', $dates['from']);
if ($dates['to'])
$query->where('to', $dates['to']);
$query->select('Active');
return $query->get()->toArray();
}
In Laravel 4, its necessary to assign the get method to a variable
public function scopeGetPosts($query, $this_user = NULL){
$results = DB::table('post')
->select('*')
->where('post_status','=','publish');
if( $this_user != NULL ){
$results->where('post_author','=',$this_user->user_id);
}
$data = $results->orderBy('created_at', 'desc')
->get();
if( empty( $results ) )
$data = 'no results';
return $data;
}
In Laravel Eloquent :
$query = ModelName::where('status',1);
if($userId){
$query->where('user_id',$userId);
}
if($limit){
$query->limit($limit);
}
$result = $query->get();