why my code get error
public function AuditorBagian_Edit($nopek)
{
$user = User::where('nopek', '=', $nopek)->get();
$bagian_user = Bagian::all()->where('kode_bagian', '=', $user->bagian)->get();
return response()->json($bagian_user);
}
I want to show data from Bagian
You can pass collection or array into response()->json() function it will convert as JSON data
public function AuditorBagian_Edit($nopek)
{
$user = User::where('nopek', '=', $nopek)->get();
$bagian_user = Bagian::where('kode_bagian', '=', $user->bagian)->get();
// or $bagian_user = Bagian::where('kode_bagian', '=', $user->bagian)->get()->toArray();
return response()->json($bagian_user);
}
Error result of code
$bagian_user = Bagian::all()->where('kode_bagian', '=', $user->bagian)->get();
Bagian::all() return instance of Illuminate\Database\Eloquent\Collection and find all records in db, then you try to filter ->where('kode_bagian', '=', $user->bagian)->get() specific records but this code wrong because method where() of Illuminate\Database\Eloquent\Collection class return instance of Illuminate\Database\Eloquent\Collection and this class does not haveget() method.
User::where('nopek', '=', $nopek)->get() also return instance of Illuminate\Database\Eloquent\Collection. To get single record use first() method instead of get()
The correct way get result is
$user = User::where('nopek', '=', $nopek)->first();
if(!empthy($user)) {
$bagian_user = Bagian::where('kode_bagian', '=', $user->bagian)->get().
}
Edited, format php code
Just remove the ::all() will do, all() and get() is the same behaviour.
Take not that all(), get(), first() is the final step to get the model data, the condition and with() and ordering() and etc must happen before all the three above mentioned
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);
}
public function showJobCategoryContent($id)
{
$jobsInfo= Job::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
return $jobsInfo->company_name;
}
public function showJobCategoryContent($id)
{
$jobsInfo= Job::where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);
return $jobsInfo['company_name'];
}
If i do that it shows --Undefined property also if i use return $jobsInfo['company_name'] now it shows blank page I know there is company_name index also i tried another index also. Why is it doing that?
Your main problem is not understanding what is returned by a paginate query. Have a good read of the docs for this https://laravel.com/docs/5.5/pagination#paginating-query-builder-results
That being said there are better ways of doing this with Laravel.
return Job::where('category_id', '=', $id)->select('company_name')->where('published', '=', 1)->get();
Will return a Collection of just company_name using the select function in the query builder.
https://laravel.com/docs/5.5/queries#selects
I have the following function in Controller:
public function getProduct()
{
return Product::join('shopping_list_items', 'products.id', '=', 'shopping_list_items.product_id' )
->join('shop_lists', 'shop_lists.id', '=', 'shopping_list_items.shopping_list_id')
->select('products.product_name', 'products.id')
->where('shop_lists.id', $this->id);
}
This code in the view works perfectly and shows product name:
{{$shoppinglists->getProduct()->first()->product_name}}
But I can't loop through it like this:
#foreach($shoppinglists->getProduct() as $sh)
{{$sh->product_name}}<br>
#endforeach
Though it doesn't show any error.
Your getProduct() method returns an instance of the Database Builder, not the collection, that is why you can do ->first(), which basically does a fetch limit 1 and gets you the object.
So, you need to call the ->get() or maybe paginate() to actually do a fetch of the data to the database and obtain the collection of objects.
So, bottom line, just do:
#foreach($shoppinglists->getProduct()->get() as $sh)
{{$sh->product_name}}<br>
#endforeach
As #Carlos explained, you need to use get() to get values from database.
public function getProduct()
{
return Product::join('shopping_list_items', 'products.id', '=', 'shopping_list_items.product_id' )
->join('shop_lists', 'shop_lists.id', '=', 'shopping_list_items.shopping_list_id')
->select('products.product_name', 'products.id')
->where('shop_lists.id', $this->id)
->get();
}
This will return you a JSON object. If you need an array output from this query, use pluck('filed name'); instead of get();
In your view, use
#foreach($shoppinglists as $sh)
{{$sh->product_name}}<br>
#endforeach
I am fetching records in controller :
$tasks = Task::where('user_id', '=', Auth::user()->id);
return view('todo',compact('tasks'));
But it returns null.
And Auth::user()->id returns 2 Which is Okay.
Am i missing something ?
You need to actually retrieve the record. What you have is an instance of \Illuminate\Database\Eloquent\Builder, but not the actual record(s) associated with the query.
To tell Eloquent to fetch the data, you need to use either get().
Like:
$tasks = Task::where('user_id', '=', Auth::user()->id)->get();
As a side note, you can simplify your query to be:
$tasks = Task::where('user_id', Auth::user()->id)->get();
Furthermore, on your User model, you could do this:
public function tasks()
{
return $this->hasMany(Task::class) // make sure you use the full namespace here or use at the top of User.php
}
And then you can simply do:
$tasks = auth()->user()->tasks;
This is a Relationship in Eloquent as explained in the docs.
I'm building a very simple web app with Laravel.
I've built two separate Controllers, which each return two separate views, as follows:
ProfileController:
class ProfileController extends BaseController {
public function user($name)
{
$user = User::where('name', '=', $name);
if ($user->count())
{
$user = $user->first();
$workout = DB::table('workouts')->where('user_id', '=', $user->id)->get();
Return View::make('profile')
->with('user', $user)
->with('workout', $workout);
}
return App::abort(404);
}
}
WorkoutController:
class WorkoutController extends BaseController {
public function workout($name)
{
$workout = DB::table('workouts')->where('name', '=', $name)->first();
if ($workout)
{
Return View::make('add-exercise')
->with('workout', $workout);
}
return App::abort(404);
}
}
What is confusing me is what I had to do in order to pass a single workout object to each view. As you might have noticed the query builders for workout are different:
$workout = DB::table('workouts')->where('user_id', '=', $user->id)->get();
and
$workout = DB::table('workouts')->where('name', '=', $name)->first();
On the profile view, I get an object using the ->get(); method, but on the add-exercise view, I must use ->first(); or I will otherwise get an array with only one index, where I can then access the object, i.e. $workout[0]->name instead of $workout->name.
Why is this? Shouldn't I be able to use either get and/or first in both controllers and expect the same type of result from both since I want the same thing from the same table?
get() returns a collection of objects every time. That collection may have 0 or more objects in it, depending on the results of the query.
first() calls get() under the hood, but instead of returning the collection of results, it returns the first entry in the collection (if there is one).
Which method you use depends on what you need. Do you need the collection of all the results (use get()), or do you just want the first result in the collection (use first())?
Model::find(numeric); returns a object
Model::whereId(numeric)->first(); returns a object
Model::whereId(numeric)->get(); - returns a collection
Model::whereId(numeric); - returns a builder