I'm currently trying to get data from the DB with a Laravel controller through a model Maintain. Is there a way to query the DB based on the request data made by an axios post from the front end, this includes both variables sub and zone, I have the ability to get the data from using sub OR zone but not both, is there a way to construct a multi where query if $request contains the necessary variables and a standard request if they are null or ""?
public function all(Request $request){
$query = [];
if($request->sub != ""){
array_push($query, ['subsystem', '=', $request->sub]);
}
if($request->zone != ""){
array_push($query, ['zone', '=', $request->zone]);
}
if(count($query) > 0){
return Maintain::all()->where($query);
}
else{
return Maintain::all();
}
}
Currently This returns with an error ErrorException: array_key_exists(): The first argument should be either a string or an integer in file but I've been using the Laravel reference and it doesn't seem to be working. I used Postman to get the readout of $query and it contains the following:
[
['sub', '=', 'Subsystem 1'],
['zone', '=', 'Zone 1']
]
Any help would be appreciated.
Try like this
public function all(Request $request){
$result = Maintain::when($request->zone, function ($q) use($request){
$q->where('zone', $request->zone);
})
->when($request->sub, function ($qw) use($request){
$qw->where('subsystem', $request->sub);
})
->get();
return($result);
}
when() method look like if-else
Edited: Let we know if you get an error: Happy coding
Related
I want to join multiple tables in laravel with query builder. My problem is that my code only works if I specify the id myself that I want like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=','1')
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
But I would want something like this(which I just can't seem to figure out)
public function showuser($id)
{
$userid = User::findOrFail($id);
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$userid)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
}
Am I making a syntax mistake? When I check the page for my json response in second page it just returns empty brackets, but when I specify the id it fetches me the right data
The findOrFail method will return the entire user model, with all its properties, since you already have the user id. You dont need to get the entire user model for that, you could just use the $id you receveid as a parameter like this:
$datauser = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($datauser);
public function showuser($id)
{
$getUserByID = User::findOrFail($id); //not used
$userData = DB::table('users')
->join('activitates','users.id','=','activitates.user_id')
->join('taga_cars','taga_cars.id','=','activitates.tagacar_id')
->join('clients','users.id','=','clients.user_id')
->where('users.id','=',$id)
->select('users.*','activitates.*','taga_cars.model','taga_cars.id','clients.name')
->get();
return response()->json($userData);
}
But the best way is to have relations set on models
public function showuser($id)
{
$userData = User::where('id', $id)->with(['activitates','taga_cars','clients'])->first();
return response()->json($userData);
}
I'm struggling a bit with some formulas, the idea is to have just one formula/function for everything, so it'll be easy to maintain and will be robust.
The problem is trying to combine AJAX calls and laravel functions.
From one side I have a AJAX Datatables controller (the calls need to be in this format):
public function userData(Request $request)
{
$event = User::select(
'users.*',
DB::raw('IFNULL(b.balance,0) as balance'),
)
->leftJoin(DB::raw('(SELECT seller_id, SUM(total) as balance FROM transactions WHERE concept IN ("TPV") AND status = "ok" GROUP by buyer_id)as b'), 'b.seller_id', '=', 'users.id')
->get();
return $this->formatView($request, $event, 'user');
}
Then, the formula I use for the rest of the web is in a Function inside a Model:
public function Balance($seller_id = false){
return Transaction::emitted()
->where('event_id', $this->id)
->where('seller_id', $this->seller_id)
->whereIn('concept', ['TPV'])
->where('status', 'ok')
->sum('total');
}
The question is: Do you have an idea of how to use just one formula/function for everything?
Try this in your controller method
Do common calculations in separate method and call it here. Then change format of response in below sections
if ($request->expectsJson()){
//send response to ajax here in json format. note that you should set ajax dataType:'json'
}
//send response for web here.
i am trying to query many to many relation for my get api call. i have three table as shown here but i am not using pivot table.
This is my Projects model class and this the function
public function projectRewd()
{
return $this
->belongsToMany('App\Rewards','rewards','project_id','reward_id');
}
And this is my Rewards model class and function
public function projectShip()
{
return $this->belongsToMany('App\Shipping_location','shipping_location','projects_id','rewards_id');
}
This is my api controller function
Route::get('projects/{id}', function($id) {
$proj = Projects::whereHas('projectRewd', function($q)
{
$q->where('id', $id);
});
return $proj;
});
i am using this link for api call
http://localhost:8000/api/projects/1
i want to extract rewards data and shipping_location data associate with project_id.
i am getting this error
"message": "Object of class Illuminate\\Database\\Eloquent\\Builder could not be converted to string"
i check and tried all related error from different post.
i also search and tried many technique. Cant solve my problem.
Please suggest me how to do this??
can i do this type of query in larvel without using pivot table??
You are getting Builder model because you forgot to add ->first() or ->get().
You should write:
$proj = Projects::whereHas('projectRewd', function($q){
$q->where('id', $id);
})->first();
Your closure-based controller returns your query-builder object. Not a project. You need to retrieve results from the query by fetching e.g. the first result (->first()) or all (->get()).
Route::get('projects/{id}', function($id) {
$proj = Projects::whereHas('projectRewd', function($q)
{
$q->where('id', $id);
})->first();
return $proj;
});
Referencing $id:
The reason why $id is unknown, is that the closure doesn't know about it.
You can pass it to the closure using use(...).
Route::get('projects/{id}', function($id) {
$proj = Projects::whereHas('projectRewd', function($q) use ($id)
{
...
Further:
Your whereHas query looks incorrect to me:
$q->where('id', $id);
Apparently $id is the project id. But the 'id' column in projectRewd is the primary key of projectRewd (unless you have modified the defaults).
I assume you want to query all projects that have at least one projectRewd:
Route::get('projects/{id}', function($id) {
$proj = Projects::has('projectRewd')->first();
return $proj;
});
And if you want to eager load the joined tables:
Route::get('projects/{id}', function($id) {
$proj = Projects::with('projectRewd. projectShips')->has('projectRewd')->first();
return $proj;
});
I'm trying to read data from MySql with "Laravel 5.3". Then I serve them using json.
Here is my code:
public function getUserTimeline(Request $request)
{
$input=$request->all();
$id = Input::get('id');
$usertimeline = DB::table('users')
->join('timeline','users.id', '=', 'timeline.user_id')
->where('users.id',$id)
->get();
return $usertimeline;
}
But db returns duplicate data to me like this:
[
{
"0":1,
"1":"Berkay Erdi",
"2":"berkayerdi",
"3":"berkayerdi#gmail.com",
"id":1,
"name":"Berkay Erdi",
"username":"berkayerdi",
"email":"berkayerdi#gmail.com"
}
]
Bottom key-value datas are true one. I do not understand why are the data repeated. Is the error in the database? Or what else.
Thanks in advance.
Add the SELECT clause in order for you to get your wanted results.
public function getUserTimeline(Request $request)
{
$input=$request->all();
$id = Input::get('id');
$usertimeline = DB::table('users')
->select('users.*')
->join('timeline','users.id', '=', 'timeline.user_id')
->where('users.id',$id)
->get();
return $usertimeline;
}
Please master the basics of PHP and SQL first before diving into any frameworks. Also read the Laravel Documentation thoroughly.
i want to sort the users through voornaam(firstname). but im getting the data via a relation.
How do i make my query so that, the relation users are sorted by firstname by alphabet
my function:
public function sortfirstname($id) {
$ingeschrevenspelers = UserToernooi::with('users')->where('toernooiid', '=', $id)->get()->all();
//This query ^^
$toernooi = Toernooi::findOrFail($id);
dd($ingeschrevenspelers);
return view('adminfeatures.generatespelerslijst', compact('ingeschrevenspelers', 'toernooi'));
}
What i want to sort
any help is appreciated
thanks in advance
Writing code in your own language doesn't make it very easy for other developers to understand your code.
That being said, you can try the orderBy() method on your relationship
In your model where you define the relationship:
public function relationship()
{
return $this->belongsTo(SomeClass::class)->orderBy('name', 'DESC');
}
Don't fire all() function at the end thus obtaining a Collection instance of result
//query without the all function
$ingeschrevenspelers = UserToernooi::with('users')->where('toernooiid', '=', $id)->get();
//
$ingeschrevenspelers = $ingeschrevenspelers->sortBy('users.firstname');
An alternative to Jordy Groote's answer if you do not want to modify the Model class itself, you can query it with a closure.
$ingeschrevenspelers = UserToernooi::with(['users' => function($q) {
$q->orderBy('voornaam', 'asc');
}])->where('toernooiid', '=', $id)->get()->all();
Reference: https://laravel.com/docs/5.3/eloquent-relationships#constraining-eager-loads
Sidenote: I don't think you need a ->all() when you already did a ->get()
$ingeschrevenspelers = UserToernooi::with(['users' => function($query){
$query->orderBy('voornaam', 'asc');
}])->where('toernooiid', '=', $id)->get()->all();