How to call a function after getting model from database? - laravel

i'm getting model using this code:
$user = \App\Http\Models\User::where('id', $id)->with('services')->get();
and i want to call this function for example
$user->getServiceList(); //this metod gets ALL services, not hasMany
but it causes an error
Method getServiceList does not exist

get() loads a collection, so you need to iterate over it to get objects:
$users = \App\Http\Models\User::where('id', $id)->with('services')->get();
foreach ($users as $user) {
echo $user->getServiceList();
}

It's much better to use find method if you are searching by user id:
$user = \App\Http\Models\User::with('Service')->find($id);
$user->getServiceList();

Related

BadMethodCallException Call to undefined method App\User::map()

I want to add additional data to $user collection so can get the profile fields in the view
I have tried using $user['profileFields'] = $this->getProfileFields() and pass $user to the view using compatct or with and this is working fine.
DD
However, I have found some reference over the net saying I can extend using map but when I tried it is giving the following error
BadMethodCallException
Call to undefined method App\User::map()
So here is what I am trying to understand
Question:
Is the below code is wrong and won't work for what I am looking for and the first approach is the solution? Is there any
recommended method to add additional data to the $user collection?
public function show(User $user)
{
$user->map(function ($user){
$user['profileFields'] = $this->getProfileFields();
return $user;
});
return view('admin.user.show', compact('user'));
}
collection methods are works on the collection, here you're getting the object of user.
$user->profileFields = $user->getProfileFields();
return view('admin.user.show', compact('user'));
If the profileFields is in another table and having a foreign key with model ProfileField, then try to add a one to one relation to the User model.
Inside the User model, add a function
public function profileFields()
{
return $this->belongsTo('App\ProfileField', 'foreign_key','other_key');
}
This will give you the profileFields in every user when calling using eloquent.

Looking up model in Laravel after returning array of objects in Controller

I am trying to do something I've never done before in Laravel and cannot figure out how to do it.
I have the following code in my Controller:
public function show($id)
{
//Get application for drug
$application = PharmaApplication::where('ApplNo', $id)->first();
//Get all products for given application (i.e. the different quantities and forms drug comes in)
$product = PharmaProduct::where('ApplNo', $id)->get();
foreach($product as $product){
$product->ProductNo;
}
//Get Marketing Status for drug
$marketingStatus = DB::table('pharma_marketing_statuses')
->where('ApplNo', $id)
->where('ProductNo', $product->ProductNo)
->get();
//Lookup marketing status Description
$marketingStatusDescription = PharmaMarketingSatusLookup::where('MarketingStatusID', $marketingStatus->MarketingStatusID);
return view('profiles.drug', compact('application', 'product', 'marketingStatus', 'marketingStatusDescription'));
}
I am trying to accomplish the following:
Get the application for a drug - this part of my code works
Return an array of objects for the products (i.e. 7 products that belong to one application). I can do this but get stuck going to the next part.
Next, I have to use the array of objects and search a table with the following columns: MarketingStatusID, ApplNo, ProductNo. I know how to query this table and get one row, but the problem is I have an array that I need to search. I imagine I have to use a loop but don't know where.
Finally, I use the MarketingStatusID to retrieve the MarketingStatusDescription which I will know how to do.
I am also getting an error message that says:
Class 'App\Http\Controllers\profiles\PharmaMarketingSatusLookup' not found
In my Controller, I have use App\PharmaMarketingStatusLookup; so I am not sure why it is searching the Controllers folder
You have a typo in your class
From PharmaMarketingSatusLookup change to PharmaMarketingStatusLookup
App\Http\Controllers\profiles\PharmaMarketingStatusLookup
USE whereIn
use App\PharmaApplication;
use App\PharmaProduct;
use App\PharmaMarketingSatusLookup;
public function show($id)
{
$application = PharmaApplication::where('ApplNo', $id)->first();
$products = PharmaProduct::where('ApplNo', $id)->get();
$productid = array();
foreach($products as $product){
$productid[] = $product->ProductNo;
}
$marketingStatus = DB::table('pharma_marketing_statuses')
->where('ApplNo', $id)
->whereIn('ProductNo', $productid)
->get();
$marketingStatusDescription = PharmaMarketingSatusLookup::where('MarketingStatusID', $marketingStatus->MarketingStatusID);
return view('profiles.drug', compact('application', 'product', 'marketingStatus', 'marketingStatusDescription'));
}

how to display name from database in laravel

i want to display data from my database
controller
public function generatePDF(Request $request)
{
$id = Auth::user()->id;
$name = User::select("NAME")->where("id", $id)->get();
$pdf = PDF::loadView('generatePDF', ['name'=>$name]);
return $pdf->stream('generatePDF.pdf');
}
blade
<h2>{{name}}</h2>
result
[{"NAME":"name_from_database"}]
can i display without [{"name":}], so just the value of data (name_from_database) ?
Simple use find like this
$name = User::find($id)->name;
Or direct from auth
$name = \Auth::user()->name;
To get logged in user id you can use \Auth::id()
you can use:
$user_id = User::findOrFail($id)->first();
$name=$user_id->name;
test the laravel log file:
\Log::info($name);
Use first() instead of get(), because get() will return an array and first() will return the object.
DRY Code line no.1 and no.2. simple use:
$name = auth()->user()->name;
to get the name of the currently authenticated user.
Send $name to you view is fine
$pdf = PDF::loadView('generatePDF', ['name' => $name]);
Correct your code in blade file
{{ name }} -> {{ $name }}
I hope this might help you. :)
Hello Aldi Rostiawan,
$nameGet = User::select("NAME")->where("id", $id)->get();
$nameFirst = User::select("NAME")->where("id", $id)->first();
Here in both line of code the difference is only Get and First.
Get method returns an Array of objects. So for example if the query apply on many records then the code will give you many objects in an array. Or if query will be true for only one record then also it will return an array with one object.
If you know that id is primary key of he table then only one record will be fetched then you can use First function instead if Get method.
First function always return an Object. In case if query apply on many records then also first method will return you only first record as an Object.
And it seems that you have required an Object only.
You should try this:
Controller
public function generatePDF(Request $request)
{
$id = Auth::user()->id;
$rsltUser = User::where("id", $id)->first();
$pdf = PDF::loadView('generatePDF', ['rsltUser'=>$rsltUser]);
return $pdf->stream('generatePDF.pdf');
}
blade
<h2>{{$rsltUser->name}}</h2>
use VALUE() to display name only.
in your case:
<h2>{{$rsltUser->value('name')}}</h2>
your name variable is an array containing a single object with a NAME attribute .. so to diplay that value, you should change your script to
<h2>{{name[0]['NAME']}}</h2>

Laravel 5.2 How to get all user which contains permission Many to Many

I have table with many to many relationship.
User many to many Permission
I already define many to many relationship on both model, and create the pivot table also.
What I want is get all user which contain permission name
What I have done so far is
User::all()->permissions->contains('name', 'access.backend.admin')->get();
But it give me
Undefined property: Illuminate\Database\Eloquent\Collection::$permissions on line 1
What wrong with my code?
User::All() returns a collection not model object. You have iterate over the collection to get the model object and use ->permissions().
For exapmle:
$users = User::all();
foreach ($users as $user) {
$user->permissions->contains('name', 'access.backend.admin'); // returns boolean
}
Or you can get a single model from DB as:
$user = User::first();
$user->permissions->contains('name', 'access.backend.admin'); // returns boolean
Update 1
To get users which contain desired permission use filter() method as:
$filtered_users = $users->filter(function ($user) {
if ($user->permissions->contains('name', 'access.backend.admin')) {
return $user;
}
});
Update 2
You can also write a query which returns the desired result as:
$filtered_users = User::whereHas('permissions', function($q) {
$q->where('name', 'access.backend.admin');
})->get()
I have a similar case of questions and tags, they have many to many relationship.
So when i have to fetch all question with a particular tag then i do this
$tag = Tag::where('name','laravel')->get()->first();
I first retrieved the Tag model with name laravel.
and then retrieved all questions having tag laravel.
$questions = $tag->questions;
Similarly you can do this
$permission = Permission::where('name','access.backend.admin')->get()->first();
$users = $permission->users;

Laravel 4 #foreach

Using a resourceful UsersController and $users.
It seems that when $users has only 1 entry, the #foreach loop doesn't work?
In UsersController:
public function show($id) {
$users = User::find($id);
return View::make('users')->with('users',$users);
}
If I just use "return $users", the value of $users is:
{"id":"1","username":"user1"}
In users.blade.php:
#foreach($users as $user)
{{$user->username}}
#endforeach
When there are 2 or more users it worked, but with URI app.com/users/1, it only returns one (see above) and the new error is:
"Trying to get property of non-object"
Why is this an error in users.blade.php?
It's more a question of what User::find($id) is returning..
Query builder methods return an instance of the Collection class, which represents a collection of Models. For instance, here we get back a Collection containing one Model.
$users = User::where('id', '=', $id)->get();
However the find() method returns a single Model
$users = User::find($id);
A single Model isn't iterable in the same way as a Collection, which returns a Model with each iteration, hence the error you're seeing!

Resources