Laravel Create OR update related model - php

I have the following function to create a new related model;
//Create the results entry
$result = new Result([
'result' => $total,
'user_id' => $user->id,
]);
//attach it to the fixture - parse through looking for the user_id or opponent_id
//to match the current user in the loop.
$fixture = LeagueFixture::where('league_id', $league_id)
->where('gameweek', $gameweek)
->where(function($q) use ($user){
$q->where('user_id', $user->id)
->orWhere('opponent_id', $user->id);
})
->first();
$fixture->results()->save($result);
The ->save() at the end does most of the magic, attaching the correct fixture_id to the result table. The problem is that if the function is run again, it creates new entries for the same results.
There is a firstOrCreate() method, but i don't know how to use this when saving a related model.
Thanks

It's exactly like this: http://laravel.com/docs/5.0/eloquent#insert-update-delete.
//Create or find a existing one...
$result = Result::firstOrCreate([
'result' => $total,
'user_id' => $user->id,
]);
//grab fixture...
$fixture = LeagueFixture::where('league_id', $league_id)
->where('gameweek', $gameweek)
->where(function($q) use ($user){
$q->where('user_id', $user->id)
->orWhere('opponent_id', $user->id);
})
->first();
//associate (set fixture_id in $result equals to $fixture's key)
//any previous association will disappear.
$fixture->results()->associate($result);
//save to write changes in the database.
$result->save()
you can check here (https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L559). Laravel will search in your database and return if it found it or create a new.

Related

stuck at laravel, trying to store an id in a variable

I want to store the user_id in the profile table into a variable. In my index function I have:
$userid = Profile::where('user_id', auth()->user()->id)
->first();
return view ('profile.index',[
'user' => $user,
'userid' => $userid,
'about' => $about,
and in my index view:
#if(Auth::user()->id == $userid)
<h3>hello</h3>
#endif
Yet, I get this error:
Object of class App\Models\Profile could not be converted to int (View: C:\xampp\laravelprojects\testfrihand\resources\views\profile\index.blade.php)
Change it to get user_id from the model instance
$userid = Profile::where('user_id', auth()->id)
->first()->user_id;
Notice1: When you call first() method, you'll get an instance of eloquent model. You should tell it what attribute do you want. Here, you want user_id. Either ->first()->user_id and ->first()->get('user_id') will give your desired answer.
Notice2: You can get id of current authenticated user by calling auth()->id
Not actually understand what do you need exactly.
But anywhere
$userid = Profile::where('user_id', auth()->user()->id)
->first();
Here you get a Profile Object, not an id.
Please specify your question: do you want to store user_id in this code, or to get user_id and use it in condition?
$user = auth()->user();
$whatEverYouWant= Profile::where('user_id', $user->id)->first();
return view ('profile.index',[
'user' => $user,
'userid' => $user->id,
'about' => $about
]

Eloquent relation clarification

Following is my query
$user = User::with(['session' => function ($query) {
$query->select('id','device_id');
$query->where('api_token', '=', '123456');
}])->get();
session: hasMany relation with User.
I am expecting a user with a session having api_token = 123456. Instead I am getting whole users here. I know I am doing something wrong.
I am referring this doc. In the doc it is saying that we can add constraint to the query. But here $query->where('api_token', '=', '123456'); this where is not working.
You are not filtering the User, you are filtering the result of the eager loading of 'session'. Eager loading does not have any effect on the base result set in anyway.
It sounds like you want to filter User by the 'existence' of a relationship in the database.
User::whereHas('session', function ($q) {
$q->where('api_token', '12345');
})->get(); // ->first();
Get all Users that have a Session where 'api_token' == '12345'.
Laravel 5.5 Docs - Eloquent - Relationships - Querying Relationship Existence
Finally I got it worked.
$sessionSelect = function ($query) {
return $query->select( 'user_id', 'device_id');
};
$detailSelect = function ($query) {
return $query->select('user_id', 'dob', 'gender');
};
$sessionWhere = function ($query) use ($key) {
return $query->where('api_token', $key);
};
$users = User::with(['session' => $sessionSelect,'detail'=>$detailSelect])
->whereHas('session', $sessionWhere)
->first();

Updating rows in laravel mysql database

I've set up a database and want to update the column status for each row in my UsersController:
I started with this:
User::where('id', '=', 1)->update(['status' => $status]);
This is working, but I need some loop to change all the rows, something like this:
foreach $id from the table
run some code to change individual $status variable
set individual $status value in the 'status' column in each row:
User::where('id', '=', $id)->update(['status' => $status])
end foreach
So for me its unclear how to go through the table via the foreach. Then save the calculated status from my code to each individual id?
#Serge solution is fine for few records but you should be able to use chuck as #ceejayoz suggested
User::chunk(100, function ($users) {
$users->each(function ($user) {
$user->status = getStatus($user);
$user->save();
});
});
Unless the table contains millions of rows... a simple procedural way of doing it is...
$users = Users::get(); // Gets a collection of all users...
foreach ( $users as $user ) {
//compute your status
$user->status = get_your_user_status($user->id);
$user->save();
}
You could also consider using a more functional approach with map for example...

Laravel Eloquent - Filter is ignored when returning results

I am trying to return a (JSON) string of a specific user with his/her posts. However the Post model contains several columns that aren't of interest for API implementations and I want to exclude these columns from the result.
Why does the following still return no columns at all in the Posts relation
I've tried multiple ways of retrieving specific columns on the Post model.
$result = User::with([
'posts' => function($q) {
$q->addSelect('title', 'tag');
}])
->where(['api' => 1, 'id' => $id])
->first(['id', 'username', 'role']);
return $result;
dumping
$q->get()
shows exactly what I want, however the returned $result includes none of the columns in the Post model.
My Laravel version is 5.2
try changing addSelect to just select
$result = User::with([
'posts' => function($q) {
$q->select(['title', 'tag', 'user_id']); // You might have to also include `user_id` here
}])
// ->where(['api' => 1, 'id' => $id]) change this
->where('api', 1)
->where('id', $id)
->first();
return $result;
Because addSelect is adding items to an existing select, rather than specifying what you actually want in the select.

Updating record in Laravel from a select using laravel's lists not working

In one of my laravel pages I am updating a record. The form is bound to the model, and all fields are updating properly except those where I am presenting a select using lists that populates the select from the database:
{{ Form::select('resume_id', $resume_lists) }}
I just have no idea why these will not update. They are pulling the appropriate values from mySQL. Any ideas?
Thank you.
I have my code in routes, not in a controller
Route::get('application/edit/{id}', array('as' => 'application.edit', function($id)
{
$user = Auth::user();
$company_lists = Company::where('user_id', '=', $user->id)->get()->lists('company', 'id');
$resume_lists = Resume::where('user_id', '=', $user->id)->get()->lists('name', 'id'); //changed resume to name
$companies = Company::where('user_id', '=', Auth::user()->id)->get(); //just added
//$currentintdate=$application['followupBy']; /////
Session::put('appid', $id); /////
return View::make('application-edit', array('company_lists' => $company_lists), array('resume_lists' => $resume_lists))
->with('application', Application::find($id));
}));
try this:
$resume_lists = YourResumeModel::lists('title', 'id');
{{ Form::select('resume_id', $resume_lists) }}
frist column is your text for dropdown
and next column is your row id
just var dump the resume list data in controller, make sure its available at the controller, so after you initialize the variable/array
return var_dump($resume_lists); // check if its valid array with id as key and label as value, if available, go view and do the same
Use: $resume_lists = Resume::all()->where('user_id', '=', $user->id)->lists('name', 'id');
Or: $resume_lists = Resume::where('user_id', '=', $user->id)->lists('name', 'id')->toArray();
well, my records were not updating because I had a column as not nullable and I was not passing any value while testing. I got no error at all about this so I had no idea.

Categories