I am beginner in Laravel Framework.I have searched for my problem and get some solution but those are not solve my problem.So,
profiles table:
I want to need to fill up userID column when any user create a profiles.For this i am trying to code something like this:
Profile model:
public function users(){
return $this->belongsTo('App\User','userID');
}
And User Model:
public function profiles()
{
return $this->hasMany('App\Profile');
}
In this way its keep null value every time.How can i solve this?
Thanks in advanced.
So assuming you have the following (which you kind of do)
public function profiles()
{
return $this->belongsTo(\App\User::class); // we do not need to provide the user_id because laravel assume we are using that
}
<?php
// Profile.php (Model)
public function user()
{
$this->belongsTo(\App\User::class); // Again we do not need to provide the information because of the table / column names we are using
}
You have a few options, you can either when creating the profile, assign the user_id (as long as it is in the fillable fields.
$profile = new Profile;
$profile->user_id = \Auth::getId(); // current logged in user
$profile->somethingElse = 'abc';
$profile->save();
Or since we have a relationship you should be able to do something like this
$profile = new Profile;
$profile->somethingElse = 'abc';
// We will use the current logged in user again
Auth::user()->profiles()->save($profile); // will automagically fill in the user_id with the logged in user's id.
Hopefully that sheds some light
While inserting Data into Profile Table, you just need to do as follows:
$profile = new Profile();
$profile->userID = Auth::user()->id;
$profile->other_columns = 'values'
.....
$profile->save();
There is no need to join the tables for inserting the value in Profile Table for here. Hope this helps you
Related
Very silly situation, The point is I can not change the database architecture because its a running e-commerce business having more then 1m active users.
Here is my situation.
Table User:
Table Store:
Both have same primary key, mean we can call the one to one relation.
But now I have to create belongs to many relation form Store to User.
store table have two columns
slug
parentId
Now I need to get all users having slug of store
So my query is
select * from users where id IN (select id from store where slug = ?);
How can I create a relation in this situation.
Hey there i would try to answer in detail as much as possible.
Create the following relationships:
For store:
public function users(){
return $this->hasMany(User::class, 'id' ,'slug');
}
For user:
public function store(){
return $this->belongsTo(Store::class);
}
Create a new controller and write a new function as below:
public function getStoreUsers(){
$users = Store::where('slug','yourvalue')->firstOrFail()->users;
return response()->json($users);
}
The function above will return a collection of users which have theirs 'id' equals to store 'slug'
In case if you have many stores you can do the follwing:
public function getStoreUsers(){
$stores = Store::all();
$storeUsers;
foreach($stores as $store){
$users = $store->users;
$storeUsers[$store['id']] = array($users);
return response()->json($storeUsers);
}
}
This function will return an array of users of each store.
I have answered according to my understanding of your question if any erros occur please reply below so i can fix if possible. I Hope this is what you wanted if not let me know.
UPDATE:
This is what i could understand from your request.
Store a , store b , store c has slug = xyz.
you have 50,000 users. 10,000 of them has slug xyz. and you need the information of those 10,000 users. if thats the case then the code below will help you out.
public function getStoreUsers(){
$slugtomatch = 'xyz';
$result;
$stores = Store::where('slug',$slugtomatch)->get();
foreach($stores as $store){
$users = $store->users;
$result = array($users);
}
return response()->json($result);
}
This will return an array of users those have the $slugtomatch value in their slug fields.
This code does not seem to capture the user id from the session so I can use it as a foreign key in the database for the place the user is adding a comment to.
public function store(Request $request, $place_id) {
// find place in the database
$place = Place::find($place_id);
// find user in the database
$user = User::find(\Auth::id());
// create review instance
$review = new Review([
'review' => request('review'),
'rating' => request('rating')
]);
// save review (creating relationship) in the places table as reviews
$place - > reviews() - > save($review);
// save review (creating relationship) in the users table as reviews
$user - > reviews() - > save($review);
$reviewData = Review::find($review - > id);
if (request() - > wantsJson()) {
return $reviewData; // Returns JSON, thanks to Laravel Magicâ„¢
}
// return view
return view('place');
}
When creating models for relationships, use create instead of save.
$user->reviews()->create($review);
The create method will associate the relevant relationship id.
I can see that you are saving the $review twice. Once in place_reviews and once in user_reviews. Consider changing your database logic, so reviews belongs to User and Place instead. This would be a lot more sensible structure:
Controller
$review = new Review([
'review' => request('review'),
'rating' => request('rating')
]);
$review->user()->associate($user);
$review->place()->associate($place);
$review->save();
Review model
public function user()
{
return $this->belongsTo(User::class);
}
public function place()
{
return $this->belongsTo(Place::class);
}
Review table
$table->unsignedInteger('user_id');
$table->unsignedInteger('place_id');
User and place model
public function reviews()
{
return $this->hasMany(Review::class);
}
You also have the option to use belongs to many relationships, if one Review could relate to multiple Place.
Another tip:
You may also consider using findOrFail to ensure your user is valid. This way your code will throw an Exception if there is no user id, as opposed to proceeding with a null user, which could be cause for hard-to-find errors.
$userId = \Auth::id();
$user = User::findOrFail($userId);
You should do like this.
$user = \Auth::user();
if(!is_null($user)){
$user_id = $user->id;
}
Database Table Relationship
What I did:
public function index(Request $request)
{
$company_feedback = $request->user()->company()
->get()->pluck('id')- >toArray();
$company = Company::whereIn('id',$company_feedback);
$feedback = $company->feedback;
return view('feedback.index', ['feedbacks' => $feedback]);
}
By using eloquent relationship, how to retrieve feedback data from a specific user id ? I want show feedback data which belong to current login user login id.
anyone could help? show me how to write the code in Index method in Feedback class.
Assuming you have two models User.php and Feedback.php
If you want to retrieve all feedback given by a current user
In your User.php
public function feedback()
{
//assuming you have user_id column in feedback table
return $this->hasMany("App\Feedback",'user_id');
}
In your controller
//all feedback given by the current user
$feedbacks = Auth::user()->feedback;
I want to make query in laravel 5.2 to fetch agencies table which has a foreign key with organizations table using agencies.organization_id=organizations.id. Now Users table has also foreign key with organizations table using users.organization_id=organizations.id. Now how to fetch agency table that which agencies are linked with users_id.
public function postagency(Request $request) {
$user_id = $request->user_id;
$org_id = User::where('id', $user_id)->pluck('organization_id')->first();
$postagencies = agency::where('organization_id', $org_id);
echo $postagencies;
}
For what I understand is that an user can only be under one organisation and an organisation has many agencies. If not please say so and I will alter my answer.
First of all set your relationships inside your models. An example would be:
// User.php
public function organization()
{
return $this->belongsTo('App\Organization'); // App\Organization can be changed depending on the used namespace
}
More info can be found here. If you need some more examples just ask.
After you have created these relationships you can retrieve your agency like this:
$user= User::find($request->user_id);
if (!$user) ... // Check if user exists
$agencies = $user->organisation->agencies;
If I need to explain things in more detail just ask. Hope this helps :)
I have three tables which are User table, Events table, and Events_user table. I have four columns in the Events_user table which are :
Schema::create('events_user', function(Blueprint $table){
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('events_id')->unsigned()->index();
$table->foreign('events_id')->references('id')->on('events')->onDelete('cascade');
$table->integer('eventstatus')->unsigned()->index();
$table->timestamps();
});
I have a function which add an event base on the user id, show one user can have many of the events. But the event can share to other user. The function is like this :
public function store(EventsRequests $request){
$id = Auth::user()->id;
$events= Events::create($request->all());
$events->user()->attach($id); //Store the User_ID and the Event_ID at the events_user table.
Flash::success('Your event has been created!');
return redirect('/');//Return into home page
// return $events;
}
Then it will help me update my events_user table, but how do I update the column which is eventstatus?
Can anyone show me how could I update it? Cause I want to use the eventstatus help me determine if there is '1' then cant be edit, then the edit button will disappear.
How many way can accomplish to the function?
For the show page:
I have use the function when the user click the event that exist on the calendar view, then the javascript will pass the id back and redirect to the view with the id.
public function show($id){
// $user_id=Auth::user()->name;
$showevents = Events::findOrFail($id);
return view('events.show',compact('showevents','user'));
}
How about when i want to pass the eventstatus into the view? So i can check on my view, if the eventstatus equal to one, the edit button wont show up.
Updated relationship model
User.php
public function events(){
return $this->belongsToMany('App\Events');
}
Events.php
public function user(){
return $this->belongsToMany('App\User')->withPivot('eventstatus');
}
If you want to update the field while making the association, you can pass an array of field=>value pairs as the second parameter to the attach() method. You can read in the documentation here.
$events->users()->attach($id, ['eventstatus' => 1]);
If you want to update the field for an existing association, you can pass an array of field=>value pairs to the save() method:
$user = Auth::user();
$event = $user->events()->first();
$user->events()->save($event, ['eventstatus' => 1]);
If you want to access the field to read the data, you can access it through the pivot property:
$user = Auth::user();
foreach ($user->events as $event) {
echo $event->pivot->eventstatus;
}
In addition to all of this, you need to make sure your relationship definitions include access to the extra property:
// User class:
public function events() {
return $this->belongsTo(Event::class)->withPivot('eventstatus');
}
// Event class:
public function users() {
return $this->belongsTo(User::class)->withPivot('eventstatus');
}
Edit
updated answer for additional question
To get the information you're looking for, you need to be able to get to the pivot record. The pivot record is available on the models in the loaded relationship.
Since you have the Event, you need to go through the related User models, find the user you want (assuming the logged in user), and then get the status off of the pivot attribute on that user.
public function show($id)
{
// get your event
$showevents = Events::findOrFail($id);
// get your user
$user = Auth::user();
// default status to send to view
$status = 0;
// if there is a user...
if ($user) {
// find the user in the "user" relationship
// NB: calling "find" on a Collection, not a query
$eventUser = $showevents->user->find($user->id);
// if the user is associated to this event,
// get the status off the pivot table,
// otherwise just set the default status
$status = $eventUser ? $eventUser->pivot->eventstatus : $status;
}
// add your status to the data sent to the view
return view('events.show', compact('showevents', 'user', 'status'));
}
In addition to all this, make sure both relationship definitions include the ->withPivot('eventstatus'). You want to make sure you can get at it from both sides, if need be.
Can you share your event and user model relationship code?
so , it will help me to get into deep.
OR
you can try this in event model like:
public function user()
{
return $this->belongsToMany('App\Event')
->withPivot('eventstatus')
->withTimestamps();
}
then while updating you can do something like this iam not sure but hope this help.
$events->user()->attach($id,['eventstatus' => 1]);
Thanks
For fetching extra column:
public function show($id){
$showevents = Events::findOrFail($id);
$event_status = $showevents->pivot->eventstatus;
return view('events.show',compact('showevents','event_status'));
}
but for that you have to define this column in models:
// User class:
public function events() {
return $this->belongsTo(Event::class)->withPivot('eventstatus');
}
// Event class:
public function users() {
return $this->belongsTo(User::class)->withPivot('eventstatus');
}