database query not working properly laravel - laravel

I have a database query as below:
$data = DB::table('settings')->select('value')->where('name', '=', $name)->get();
echo $data["value"];
but it gives error:
Undefined index: value
if I echo $data; then I get below result:
[{"value":"theme_default"}]

get() returns a Laravel Collection object, which has magic methods to turn itself into a string when you try to use it as such (like with an echo statement). As you can see in the JSON that you've printed, $data is an array or collection of objects, so you want the first one in the collection before trying to get the value:
$row = $data->first();
echo $row->value;

Try this:
$data = DB::table('settings')->select('value')->where('name', '=', $name)->first();
echo $data["value"];
//or
echo $data->value;

You can turn the result into an array like this:
$data = DB::table('settings')
->select('value')
->where('name', '=', $name)
->get()
->toArray();
//then use the value of the first element
dd(#$data[0]['value']);
, but I strongly suggest that you use the Laravel Collection in order to make use of its powerful methods.

Related

How to use where clause with local variable without passing a parameter in Laravel

I joined 2 tables and I want to display document_name from parent table(document_control_reviews) whose ID is currently posted in a child table (initial_approvals). The foreign key that holds the child document is 3.
If I hardcode the query with the ID = 3, I get the correct result just for testing purposes. But I want the documents to be display dynamically using $id instead of 3.
This hardcode test works fine when I use 3 as ID:
public function initial_approval(){
$approval_files = DB::table('document_control_reviews')
->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
->leftJoin('files', 'document_control_reviews.file_id', '=', 'files.id')
->select('document_control_reviews.*', 'initial_approvals.*', 'files.*')
->where('initial_approvals.document_control_review_id', '=', 3)
->get();
}
But I need a dynamic ID which is a local variable $id (as showed below):
public function initial_approval(){
$id = 3 //hardcoded. Here is where I'm stuck.
$docId = DocumentControlReview::find($id);
$approval_files = DB::table('document_control_reviews')
->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
->leftJoin('files', 'document_control_reviews.file_id', '=', 'files.id')
->select('document_control_reviews.*', 'initial_approvals.*', 'files.*')
->where('initial_approvals.document_control_review_id', '=', $id)
->get();
}
This is what I don't want. I dont need to pass any parameter. I don't need any argument in the method call.
public function initial_approval($id){
$approval_files = DB::table('document_control_reviews')
->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
->leftJoin('files', 'document_control_reviews.file_id', '=', 'files.id')
->select('document_control_reviews.*', 'initial_approvals.*', 'files.*')
->where('initial_approvals.document_control_review_id', '=', $id)
->get();
}
This piece of code won't work the way you intend to because here id is a collection not an integer.
$id = DB::table('document_control_reviews')->select('id')->get();
You think id will be an integer like $id = 3 but in fact here $id = Collection({"id"=>3},...) get() always return a collection.
What you are trying to do is unclear please elaborate with an example.
I finally figured it out. I simply use the where clause in my query where the child ID is a positive integer. And I get exactly what I wanted in this code below:
$approval_files = DB::table('document_control_reviews')
->leftJoin('initial_approvals', 'initial_approvals.document_control_review_id', '=', 'document_control_reviews.id')
->select('initial_approvals.*', 'document_control_reviews.*')
->where('initial_approvals.id', '>', 0)
->get();

How can I get the laravel join method without using foreach command?

How can I get the laravel join method without using foreach command? How can I solve it without using the Foreach command
{{$app->name}} I used to this type. But I'm constantly getting error.
Controller.php file content
public function show($id)
{
$show = Duty::where('duty_id', '=', $id)->count();
if ($show!=0){
$app = DB::table('users')
->join('duties', 'duties.appointed_user_id', '=', 'users.id')
->select('users.name', 'duties.*')
->get();
$data = Duty::where('duty_id', '=', $id)->get();
return view('duty.show', compact('data', 'app'));
}
else
{
return redirect()->back()->with('status', 'Sorun oluştu');
}
}
Property [name] does not exist on this collection instance. (View: D:\xampp\htdocs\personality\resources\views\duty\show.blade.php)
You have a list (collection) of users, not a single user. That is why you can't get just the name from it, because it doesn't know which one to get the name of. This problem has nothing to do with using the join method.
If you only expect to get one result from your query, you could change from ->get() to ->first(). This would allow you to call {{$app->name}} without breaking. But only do this if you expect a single result and use first.
If you expect more than one user, there is no way to display the names without looping in some way.
That's what relationships are for. In that case you could do User::with(:duties'). Or in your case the other way around would probably work better Duty::find($id)->with('user')

Can I put a collection or array into the where clause on laravel eloquent?

$collection=["c","a","f","h","j","o","k"]
$total_sums=Models::select('count')->whereIn('class',['c','a','f','h','j','o','k'])
->get()
->sum('count');
can I use variable $collection like this?
$total_sums=Models::select('count')->whereIn('class',[''.$collection.''])
->get()
->sum('count');
You can use both.
whereIn() accepts both Array and a Collection.
You just simply pass it as a second parameter.
$array = ["c","a","f","h","j","o","k"];
$collection = collect($array);
$total_sums=Models::select('count')->whereIn('class', $array)
->get()
->sum('count');
// works
$total_sums=Models::select('count')->whereIn('class', $collection)
->get()
->sum('count');
// also works!
No because $collection is already an array. When you try to concatenate it to a string, I believe your query will look like the following...
select count from models where class in ('Array');
What you probably actually want to do is...
->whereIn('class', $collection)

Laravel pluck an array from nested relationship

I need to get only the roomnumber arrays returned from the following query:
$roomnumbers = Room::with(['floorroomcount' => function($query){
$query->with('roomnumber')->get();
}])->where('roomtype_id', $roomtype_id)->get();
Tried:
The follow pluck is returning floorroomcount
$roomnumbers->pluck('floorroomcount');
but i need roomnumber array, how can i get?
This gives you all roomnumber results in one collection:
$roomnumbers->pluck('floorroomcount')->collapse()->pluck('roomnumber')->collapse();
You may shorten #Jonas Staudenmeir's answer like so:
$roomnumbers->pluck('floorroomcount.*.roomnumber.*')->collapse();
pluck('*') is essentially the same as collapse() in this particular context.
This is working, but with many loop and echoing directly, if anything can be simplified please let me know :
$roomnumbers = Room::with(['floorroomcount.roomnumber'])->where('roomtype_id', $roomtype_id)->get();
$floorroomcounts = $roomnumbers->pluck('floorroomcount');
$records = $floorroomcounts->map(function($floorroomcount, $value){
return $floorroomcount->pluck('roomnumber')->flatten();
})->values()->all();
foreach($records as $record){
foreach($record as $row){
echo '<option value='.$row->id.'>'.$row->roomnumber.'</option>';
}
}
//return response()->json($roomnumbers);
Try,
$roomnumbers = Room::with(['floorroomcount' => function($query){
$query->with('roomnumber')->get();
}])
->where('roomtype_id', $roomtype_id)
->get();
$records = $roomnumbers->map(function($element, $value){
return $element->map(function($e, $v){
return $e->roomnumber;
});
})->values()->all();
map() is a Laravel collection method so you need to import the collection facade on the top of the controller like: use Illuminate\Support\Collection;
In Laravel 5.1 and + you can use flatten() on collection.
method flattens a multi-dimensional collection into a single dimension:
$roomnumbers->flatten()->pluck('floorroomcount');

Laravel Eloquent "WHERE NOT IN"

I'm having trouble to write query in laravel eloquent ORM.
my query is
SELECT book_name,dt_of_pub,pub_lang,no_page,book_price
FROM book_mast
WHERE book_price NOT IN (100,200);
Now I want to convert this query into laravel eloquent.
Query Builder:
DB::table(..)->select(..)->whereNotIn('book_price', [100,200])->get();
Eloquent:
SomeModel::select(..)->whereNotIn('book_price', [100,200])->get();
You can use WhereNotIn in following way also:
ModelName::whereNotIn('book_price', [100,200])->get(['field_name1','field_name2']);
This will return collection of Record with specific fields
I had problems making a sub query until I added the method ->toArray() to the result, I hope it helps more than one since I had a good time looking for the solution.
Example
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->select('id_user')->where('id_user', '=', $id)->get()->toArray())
->get();
Query Builder:
DB::table('book_mast')
->select('book_name','dt_of_pub','pub_lang','no_page','book_price')
->whereNotIn('book_price', [100,200])->get();
Eloquent:
BookMast::select('book_name','dt_of_pub','pub_lang','no_page','book_price')
->whereNotIn('book_price', [100,200])->get();
The dynamic way of implement whereNotIn:
$users = User::where('status',0)->get();
foreach ($users as $user) {
$data[] = $user->id;
}
$available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();
You can use this example for dynamically calling the Where NOT IN
$user = User::where('company_id', '=', 1)->select('id)->get()->toArray();
$otherCompany = User::whereNotIn('id', $user)->get();
You can use WhereNotIn in the following way:
$category=DB::table('category')
->whereNotIn('category_id',[14 ,15])
->get();`enter code here`
You can do following.
DB::table('book_mast')
->selectRaw('book_name,dt_of_pub,pub_lang,no_page,book_price')
->whereNotIn('book_price',[100,200]);
Its simply means that you have an array of values and you want record except that values/records.
you can simply pass a array into whereNotIn() laravel function.
With query builder
$users = DB::table('applications')
->whereNotIn('id', [1,3,5])
->get(); //will return without applications which contain this id's
With eloquent.
$result = ModelClassName::select('your_column_name')->whereNotIn('your_column_name', ['satatus1', 'satatus2']); //return without application which contain this status.
This is my working variant for Laravel 7
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->where('id_user', $id)->pluck('id_user')->toArray())
->get();
$created_po = array();
$challan = modelname::where('fieldname','!=', 0)->get();
// dd($challan);
foreach ($challan as $rec){
$created_po[] = array_push($created_po,$rec->fieldname);
}
$data = modelname::whereNotIn('fieldname',$created_po)->orderBy('fieldname','desc')->with('modelfunction')->get();
or try pluck in laravel
here
DB::table('user')
->select('id','name')
->whereNotIn('id', DB::table('curses')->where('id_user', '=', $id)->pluck('user_id'))
->get();

Resources