I am using Laravel. I am trying to relate user model and message model to many-many relation.
When I access a users message it is saying function not defined. But the that function is defined.
This is the error I am getting
Call to undefined method Illuminate\Database\Eloquent\Collection::messages()
User Model.
public function docs(){
return $this->belongsToMany('Doc');
}
public function messages(){
return $this->belongsToMany('Message');
}
Message Model.
public function users(){
return $this->belongsToMany('User');
}
I am trying to store message for selected users. This is where the error rises.
I have also set the pivot table.
Messages Controller.
public function store()
{
//
$input = Input::only('title', 'body', 'sel_users');
$msg = Input::only('title', 'body');
$sel_users = Input::only('sel_users');
$this->messageForm->validate($input);
$insert = Message::create($msg);
$id = $insert['id'];
foreach ($sel_users as $userid) {
$user = User::find($userid);
$user->messages()->attach($id);
}
return Redirect::route('messages.index');
}
Your problem is that userid in the loop is an array not single id:
foreach ($sel_users as $userid) {
$user = User::find($userid); // find() provided with array returns collection...
$user->messages()->attach($id); // .. so here you can't call messages() on that collection
}
// it works the same as:
// User::whereIn('id', $userid)->get();
This is because Input::only(...) returns array, and you must have had an array of ids in sel_users too, so:
$sel_users = Input::only('sel_users');
// $sel_users = array('sel_users' => array( id1, id2 ...) )
What you wanted here is this:
$sel_users = Input::get('sel_users');
// $sel_users = array( id1, id2 ...)
Then the rest of your code will work as expected.
Related
I have a table for users and in that table, I have the column user_type_id which is related to another table called user_types. There are specific roles(subscriber and admin). Now, In my controller, I want to get all users with the condition that their user_type_id is equal to 2. With this way of doing it, I am getting only the first row...
My Controller:
public function show($id)
{
$subscriber = User::where('user_type_id', 2)->firstOrFail();
return view('show_subscriber', compact('subscriber'));
}
public function show($id) {
$subscriber = User::where('user_type_id', 2)->get();
return view('show_subscriber', compact('subscriber'));
}
public function show($id) {
$subscriber = User::where('user_type_id', 2)->firstOrFail();
return view('show_subscriber', compact('subscriber'));
}
firstOrFail() will return the first matching record and if no matching record is found it will simply return 404- resource not found.
public function show($id) {
$subscriber = User::where('user_type_id', 2)->get();
return view('show_subscriber', compact('subscriber'));
}
get() will return all the matching records as a collection.
see details here https://laravel.com/docs/9.x/eloquent#not-found-exceptions.
https://laravel.com/docs/9.x/eloquent#collections
I have model user and user_data. I want to take some data from user and user data. My code looks like:
User model:
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id');
}
public function getUserById($id)
{
$user = User::findOrFail($id);
return $user;
}
UserData model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
User controller
public function getUser($id)
{
//$user = $this->model->getUserById($id);
$user = User::with('user_data')->find(3);
dd($user->sex);
return view('user', compact('user'));
}
How I can get data from two tables? When i dump sex i get null, but I have it in db.
you have to add also the local key in the relationship like this
public function user_data()
{
return $this->hasMany('App\Models\UserData', 'user_id','your local key');
}
$user = User::with('user_data')->where('id',$id)->first(); // Get the data like this
After that you can check what is it in like this
$user->user_data[0]->sex // Not $user->sex
If it's not working try to swap the foreign key and local key places.
Also you have to take the data like this
I have to call a user model and get object only and then add the conditions.
How can I do this?
function manager(){
$email = 'xxxx#gmail.com';
$result = $this->user_model->getUserinformationData( );
$result1= $result->where('user.email',$email);
echo '<pre>';print_r($result1);exit;
}
function getUserinformationData(){
$querysucess = $this->db->select('*')->get('user');
return $querysucess;
}
Only get query object from model and add where or join condition another model or controller how can I do that one.
You have to pass variable from controller to model as function parameter:
//controller method
public function manager()
{
$email = 'xxxx#gmail.com';
$result = $this->user_model->getUserinformationData($email);//pass to the model
echo '<pre>', var_dump($result);
exit;
}
//model method
function getUserinformationData($email)//$email is passed from controller
{
$query = $this->db->get_where('user', ['email' => $email]);//second parameter of get_where() method as array of where conditions
return $query;
}
You have that in docs.
When I want to query for all states a specific dispatch ticket in my database, I would do it like this:
public function test() {
$dispatches = Dispatch::where('dispatch_reference', '=', 'dis_548k14s4glnhv5')->get();
foreach($dispatches->states as $state) {
var_dump($state);
}
}
But this throws an error message, that states is not being recognized. The models I created are:
Dispatch
class Dispatch extends Model {
use EventGenerator;
protected $table = 'dispatches';
protected $fillable = ['dispatch_reference', 'incident_reference', 'state'];
public $timestamps = true;
// Since the FK exists in this table, the belongsTo() method is used to state that the dispatch model is related to an address.
// Dispatch __belongs_to__ Incident
public function incident() {
return $this->belongsTo('App\Classes\Incident');
}
// Dispatch __belongs_to_many__ State
public function states() {
return $this->belongsToMany('App\Classes\DispatchState')->withTimestamps();
}
public function attachDispatchState($id) {
$this->states()->attach($id);
$this->touch();
}
// set fields on the eloquent object and save to database
// raise event that the incident was created.
public function createDispatch($command) {
// Get BodyContent from POST Request
$this->dispatchReference = $command->dispatchReference;
$this->incidentReference = $command->incidentReference;
// Create new Dispatch
$dispatch = Dispatch::create(array(
'dispatch_reference' => $this->dispatchReference,
'incident_reference' => $this->incidentReference
));
$dispatchState = DispatchState::where('state', '=', 'processing')->first();
$dispatch->attachDispatchState($dispatchState->id);
return $this;
}
Dispatch State
class DispatchState extends Model {
use EventGenerator;
// Define Table Setup with fillabe fields
protected $table = 'dispatch_states';
// Fillable fields in database
protected $fillable = ['state'];
// include timestamps
public $timestamps = true;
// Status __belongs_to_many__ Dispatches
public function dispatches() {
return $this->belongsToMany('App\Classes\Dispatch');
}
}
I would expect to see all the different states attached to one dispatch as i am using a pivot table that works fine so far. I just cannot query the results. Do I have an error in my models?
When you're calling get() you're getting a collection of Dispatch object. If you expect to only get a single object (e.g. when dispatch reference is unique), call first() instead of get():
$dispatch = Dispatch::where('dispatch_reference', '=', 'dis_548k14s4glnhv5')->first();
If, however, dispatch reference is not unique, you'll need to first iterate through collection of dispatches and then through their related states:
$dispatches = Dispatch::where('dispatch_reference', '=', 'dis_548k14s4glnhv5')->get();
foreach($dispatches as $dispatch) {
foreach ($dispatch->states as $state) {
var_dump($state);
}
}
I was hoping I could do this on one line:
$users = [];
$rawUsers = User::select('id','first_name','last_name')->where('company_id',Auth::user()->company_id)->get();
foreach($rawUsers as $u) {
$users[$u['id']] = $u['first_name'].' '.$u['last_name'];
}
I see the Collection class has a ->map function which would let me do the concatenation, but I don't know how to get the results indexed by id. Is there a way to do what I want?
You can do this using lists method on the query:
User::select(DB::raw('concat(first_name," ",last_name) as full_name'), 'id')->lists('full_name', 'id');
// returns array(id => full_name, ...)
Or use accessor on the model and lists on the collection:
// User model
public function getFullNameAttribute()
{
return $this->attributes['first_name'].' '.$this->attributes['last_name'];
}
// then on the collection call lists:
$usersRaw = User::where(...)->get()->lists('fullName','id');