Instead of get() I would like to use findOrFail but it doesn't work that way.
So what is the best way to return a 404 response if the row doesn't exist?
$log = DB::table('dmlog')
->select(
'dmlog.*',
'membership.membership',
'department.department',
'category.category',
'communication.communication',
'room.room AS room',
'room.category AS room_cat',
'roommove.room AS roommove',
'roommove.category AS roommove_cat'
)
->join('membership', 'membership.id', '=', 'id_membership')
->join('department', 'department.id', '=', 'id_department')
->join('category', 'category.id', '=', 'id_category')
->join('communication', 'communication.id', '=', 'id_communication')
->join('room', 'room.id', '=', 'id_room')
->join('room AS roommove', 'roommove.id', '=', 'id_roommove')
->where('dmlog.id', $id)->get(); // <----- HERE
return response()->json($log);
You can add a line abort_if($log->isEmpty(), 404); before the return line to abort if $log is empty
findOrFail is an eloquent method, not a DB raw class method. You need to use eloquent.
You need to reference the model directly to use findOrFail
$model = App\YourModel::findOrFail($id);
https://laravel.com/docs/master/eloquent#retrieving-single-models
Related
I have a draw system on my site. There are 2 draws in the database now, but for some reason, only the last created draw is displayed on the draw page. My code is:
public function raffling()
{
parent::setTitle('Items raffling | ');
$green_ticket = \DB::table('users')->where('id', $this->user->id)->value('green_ticket');
$kolvo=\DB::table('giveaway_items')->where('status',0)->orderBy('id', 'desc')->count();
$giveaway = Giveaway::orderBy('id', 'desc')->first();
$giveaway_users = \DB::table('giveaway_users')
->where('giveaway_id', $giveaway->id)
->join('users', 'giveaway_users.user_id', '=', 'users.id')
->get();
$giveAway = Giveaway::where('winner_id', '!=', 'NULL')->orderBy('created_at', 'DESC')->first();
$user = User::find($giveAway->winner_id);
$username = $user->username;
$userava = $user->avatar;
$usersteamid = $user->steamid64;
return view('pages.raffling', compact('kolvo', 'giveaway', 'giveaway_users', 'giveAway', 'user', 'username',
'userava', 'usersteamid', 'green_ticket'));
}
I tried make changes at $giveaway = Giveaway::orderBy('id', 'desc')->first(); and instead of first() use take(2), but i received error Undefined property: Illuminate\Database\Eloquent\Builder::$winner_id. And the same error appears if I add take(2) to the line $giveAway = Giveaway::where('winner_id', '!=', 'NULL')->orderBy('created_at', 'DESC')->first(); instead of first().
Where is my problem, how i can fix this error?
When you have used first() method means only one records retrieve.
Now as you said you want two records from the database. There are two methods available here.
1) take()
$giveaway = Giveaway::orderBy('id', 'desc')->take(2)->get();
2) limit()
$giveaway = Giveaway::orderBy('id', 'desc')->limit(2)->get();
*Your problem occurs because you have not used the get() method.
take() is a method that is available on collections not the query builder. You need to get a collection from the query builder first and then use the method on that.
$giveAway = Giveaway::where('winner_id', '!=', 'NULL')
->orderBy('created_at', 'DESC')
->get()
->take(2);
use take(2)
$giveaway = Giveaway::orderBy('id', 'DESC')->take(2)->get();
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
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
This is my query.
$mem = DB::table('user_zakathorg')
->JOIN('zakathorgs', 'user_zakathorg.zakathorg_id', '=', 'zakathorgs.ID')
->WHERE('user_id', '=', Auth::user()->id )
->SELECT('zakathorg_id', 'orgName')->get();
And the output is always one raw. like following image
If i want to accesss the zakathorg_id. I have to use a foreach loop. And I can't access
$mem[0]['zakathorg_id]
how can i use this as simply $mem['zakathorg_id']
Use first() method instead of get():
$mem = DB::table('user_zakathorg')
->JOIN('zakathorgs', 'user_zakathorg.zakathorg_id', '=', 'zakathorgs.ID')
->WHERE('user_id', '=', Auth::user()->id )
->SELECT('zakathorg_id', 'orgName')->get();
// You can access $mem->zakathorg_id now
In my controller I have wrote this following code
$usersCount = User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->count();
$locations_array_result = explode(",",$locations_array_result);
foreach ($locations_array_result as $param)
{
$usersCount = $usersCount->whereHas('location', function($q) use($param){
$q->where('location_id', '=', $param );
});
}
This code giving following error
Call to a member function whereHas() on a non-object
Can anyone help me to find out what i have done wrong!!!
$usersCount is already a number from the 1st line of your sample.
You want instead to replace $usersCount->whereHas with User::whereHas in your foreach loop.
Taking a very wild guess here, I would think you need to get all users with these requirements
->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)
plus having a location_id value which exists on an array named $locations_array_result
If this is the case, this is all you need:
User::where('activated', '=', 1)->where('group_id', '=', 1)->where('availability_date', '<=', $opportunity_date)->whereIn('location_id', $locations_array_result)->get();
EDIT
Following your comment below, I assume user has many to many relation with locations (defined in your model), so eager loading and then using a condition with a callback should do the job:
$users = User::where('activated', '=', 1)
->where('group_id', '=', 1)
->where('availability_date', '<=', $opportunity_date)
->with(array('location' => function($query) use ($locations_array_result)
{
$query->whereIn('location_id', $locations_array_result);
}))->get();