Status is not changing API in laravel - laravel

I try to build an API for an android app it shows complaint details when an employee enter remarks of the complaint then change the status into on working from a drop-down menu in the app. But it throws an error like this.i use postman to run the API
The status is not changing and remarks entry is not working
"SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: update complaints inner join monitorings on monitorings.complaint_id = complaints.temp_complaint_id set 0 = complaints.root_cause, 1 = monitorings.status, updated_at = 2018-07-17 12:35:27)"
public function complaint_onworking(Request $request)
{
$validator = Validator::make($request->all(), [
'rootcause' => 'required',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors());
}
//
$compid = $request->input('comp_id');
$user_id = $request->input('user_id');
$rootcause = $request->input('rootcasue');
$onworkrequest = Complaint::join('monitorings',
'monitorings.complaint_id', '=', 'complaints.temp_complaint_id')
->select([
'monitorings.complaint_id', 'monitorings.current_user_id','complaints.root_cause'
])
->where([
['complaints.temp_complaint_id', '=', $compid],
['monitorings.current_user_id', '=', $user_id]
])
->get();
// return $onworkrequest;
foreach ($onworkrequest as $onworking) {
if ($onworking) {
$onwork =Complaint::join('monitorings','monitorings.complaint_id', '=', 'complaints.temp_complaint_id')
->where([['complaints.temp_complaint_id', '=', $compid], ['monitorings.current_user_id', '=', $user_id]])
->update([['monitorings.root_cause', '=', $rootcause],['monitorings.status', '=', 1]]);
// $cmpt=array('routcause' =>$rootcause);
$success['routcause']=$onwork->root_cause;
return $this->sendResponse($success, 'Complaint is in onworking');
} else {
$success = "";
return $this->sendResponse($success, 'No change in status');
}
}
}

A couple of things I spotted in your Eloquent query.
Model::update should be passed an array of fields to be updated as keys and values to update with.
/**
* Update the model in the database.
*
* #param array $attributes
* #param array $options
* #return bool
*/
public function update(array $attributes = [], array $options = [])
See Model::update method signature / Examples
$onwork = Complaint:::join(
'monitoring',
'monitoring.complaint_id', '=', 'complaints.temp_complaint_id')
->where([
'complaints.temp_complaint_id' => $compid,
'monitoring.primary_user_id' => $user_id
])
->update([
'monitoring.routcause' => $rootcause,
'monitoring.status' => 1
]);
Also, See Model::select method signature
$onworkrequest = Complaint:join(
'monitoring',
'monitoring.complaint_id', '=', 'complaints.temp_complaint_id')
->select([
/* THIS ISN'T RIGHT
['monitoring.complaint_id', '=', $request->input('comp_id')],
['monitoring.primary_user_id', '=', $request->input('user_id')],
['routcause', '=', $request->input('rootcause')] */
])
->where([
['complaints.temp_complaint_id', '=', $compid],
['monitoring.primary_user_id', '=', $user_id]
])
->get();
For the select query, you either pass an array of columns to select or arguments of columns to select. e.g.
...
->select('monitoring.complaint_id', 'monitoring.primary_user_id', 'routcause')
There are more examples of the Illuminate\Database\Query\Builder API in the tests here.

I have fixed the error and works fine.there was a problem in the update query and I fixed, thanks for the help guys really appreciate it
$onwork=Complaint::where([['temp_complaint_id','=',$compid],['status','!=','5']])
->update(['root_cause'=>$rootcause,
'status'=>'7']);

Related

Laravel relathionship with query builder get error

I have 3 tables this table is related to, I will call this table with
belanja (parent)
anak_belanja (child)
supplier (has relation with parent)
I can create this relation from parent and child but on table supplier I get an error. Usually I use "with" and I get no error, but now I use query builder and I have a problem
My Belanja Model
public function supplier()
{
return $this->belongsTo(\App\Models\Suplier::class ,'supplier_id');
}
My Anak_Belanja model
public function belanja()
{
return $this->belongsTo(\App\Models\Belanja::class ,'belanja_id');
}
and this is my controller
public function render()
{
$user_id = Auth::user()->id;
$sub = SubRincianUraianKegiatan::where('user_id', $user_id)
->where('id' , $this->newid)
->pluck('uraian', 'id');
$sup = Supplier::all()->pluck('nama' ,'id');
$data = DB::table('belanja AS t')
->select([
't.id',
't.uraian',
't.tgl_belanja',
't.supplier_id',
DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order')
])
->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')
->where('sub_id', $this->newid)
->where('uraian', 'like', '%'.$this->search.'%')
->groupBy('t.id')
->groupBy('t.uraian')
->groupBy('t.tgl_belanja')
->groupBy('t.suplier_id')
->paginate(10);
return view('livewire.detail-belanja-lw',
['data' => $data ,
'sup' => $sup,
'sub' => $sub,
]);
}
In my blade I try to add supplier like that
{{$i->supplier->nama}}
but I get an error
Undefined property: stdClass::$supplier
Can someone explain my mistake?
$data = DB::table('belanja AS t')
->select([
't.id',
't.uraian',
't.tgl_belanja',
't.suplier_id',
DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order'),
DB::raw('s.nama as nama')
])
->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')
->where('sub_id', $this->newid)
->where('uraian', 'like', '%'.$this->search.'%')
->groupBy('t.id')
->groupBy('t.uraian')
->groupBy('t.tgl_belanja')
->groupBy('t.suplier_id')
->paginate(10);
try this.

Map usertype from query and return response laravel

$user = User::select('user_id', 'name', 'email', 'username', 'type')
->where('name', '=', $name)
->where('active', 1)
->first();
It will return first record. But what else if we have 4 records.
Mean there are four records in database with same name But i would like to display that whose type == 6 if type is not equal 6 then it should take first();
How this possible please guide
Just updated the Rwd code try this code
$query = User::select('user_id', 'name', 'email', 'username', 'type')
->where('name', '=', $name)
->where('active', 1);
$users = $query->where('type', 6)->get();
if (!$users->isEmpty()) {
$user = $query->first();
}

Laravel Database Query Builder error with table name

I'm making a "simple" api for laravel. This api has to handle with filters, pagination and sorting the result. To make this I use laravel query builder. The problem is that it's making a select without a table name, for example:
select * order by `id` asc
My code:
public function index()
{
$request = request();
$query = DB::table('customers')->newQuery();
// Orden
if (request()->has('sort')) {
// Multiorden
$sorts = explode(',', request()->sort);
foreach ($sorts as $sort) {
list($sortCol, $sortDir) = explode('|', $sort);
$query = $query->orderBy($sortCol, $sortDir);
}
} else {
$query = $query->orderBy('id', 'asc');
}
//Filtros
if ($request->exists('filter')) {
$query->where(function($q) use($request) {
$value = "%{$request->filter}%";
$q->where('name', 'like', $value)
->orWhere('address', 'like', $value);
});
}
$perPage = request()->has('per_page') ? (int) request()->per_page : null;
$pagination = $query->get()->paginate($perPage);
$pagination->appends([
'sort' => request()->sort,
'filter' => request()->filter,
'per_page' => request()->per_page
]);
return response()->json(
$pagination
);
}
Error:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error:
1096 No tables used (SQL: select * order by id asc) in file
C:\xampp\htdocs\iService\vendor\laravel\framework\src\Illuminate\Database\Connection.php
on line 664
UPDATE:
return DB::table('customers')->get();
If i use this, the api works fine, I have more apis working. The problem is that I need Query Builder to handle filters, sort, etc...
The problem was the way I instance a new query.
$query = DB::table('customers')->newQuery();
Correct:
$query = Model::query();
For my example:
$query = Customer::query();

laravel 404 error page , redirect

looking for some help, I'm fetching a survey and questions, from method, when select some survey by id, from a route. But when I delete a survey, and when writing in url like http://localhost/survey_details/27 ( 27 is survey Id , which not exist anymore), I'm getting not some expection or redirection or Page not found info, but getting error where undefined variable $dat. But I need some how to show 404 page not found, or just redirect to other page if id not exist. Can some one help me?
here is my route:
Route::get('survey_draft/{id}', 'SurveyController#editSurveyDraft');
Here is my controller:
public function viewSurvey($id)
{
$object = DB::table('question')
->where('survey_id', '=', $id)
->where('name', '!=', NULL)
->get();
$teamName = DB::table('survey')->where('surveyId', '=', $id)
->join('team', 'survey.teamId', '=', 'team.teamId')
->join('company', 'company.id', '=', 'team.companyID')
->get();
$company = Auth::user()->company;
$data = Survey::where('surveyId', '=', $id)->get();
$teams = Auth::user()->teams;
$checkUserTeam = DB::table('teammembersall')
->where('UserId', '=', Auth::user()->id)
->get();
$members = Survey::where('surveyId', '=', $id)
->join('team', 'team.teamId', '=', 'survey.teamId')
->join('teammembersall', 'teammembersall.TeamId', '=', 'team.TeamId')
->join('users', 'users.id', '=', 'teammembersall.UserId')
->select('users.*')
->whereNotExists(function ($query) use ($id) {
$query->select(DB::raw(1))
->from('answer')
->whereRaw('answer.answerAboutUserId = users.id')
->where('answer.surveyId', '=', $id)
->where('answer.member_id', '=', Auth::user()->id);
})
->get();
$questions = DB::table('answer')->get();
return view('survey_details', ['object' => $object, 'data' => $data, 'teams' => $teams, 'members' => $members, 'questions' => $questions, 'checkUserTeam' => $checkUserTeam, 'teamName' => $teamName, 'company' => $company]);
}
To solve your immediate issue, you could add one of these this after $object ... get() depending on your result. One of them should work.
if(empty($object)){ abort(404); }
or
if(!$object->count()){ abort(404); }
However, your code would be much simpler if you used 2 basic laravel technologies.
ORM instead of DB::...
Route model binding. (which would handle your 404 for you)
https://laravel.com/docs/5.6/eloquent
https://laravel.com/docs/5.6/routing#route-model-binding

Laravel 5.2 Eloquent Use of Select in Eagerly Loaded Query

I can get this to work using a select:
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with('profile')
->get();
I'd like to only retrieve a couple keys in a user profile that is eagerly loaded. I'd like to do something like this:
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with(['profile', function ($query) {
$query->select(['id', 'user_id', 'first_name', 'last_name']);
}])->get();
Or:
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with(['profile', function ($query) {
$query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
}])->get();
But this doesn't seem to work, and I get this error:
ErrorException in Builder.php line 1034:
explode() expects parameter 2 to be string, object given
Thrown in /Illuminate/Database/Eloquent/Builder.php:
/**
* Parse the nested relationships in a relation.
*
* #param string $name
* #param array $results
* #return array
*/
protected function parseNestedWith($name, $results)
{
$progress = [];
// If the relation has already been set on the result array, we will not set it
// again, since that would override any constraints that were already placed
// on the relationships. We will only set the ones that are not specified.
foreach (explode('.', $name) as $segment) { // <--- line 1034
$progress[] = $segment;
if (! isset($results[$last = implode('.', $progress)])) {
$results[$last] = function () {
//
};
}
}
return $results;
}
Is there a way to accomplish this?
Use "addSelect" instead of "select" inside the eager load constraint closure
User::whereNotIn('id', $ids)->select(['id', 'email'])
->with(['profile' => function($query) {
$query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
}])->get();
You have to include the foreign key on the addSelect otherwise nothing will be loaded

Resources