Can't update column 'Updated_at' in laravel eloquent - php

I'm still new to this laravel framework, so I was having this issue where I was unable to update the column "updated_at" which is automatically created by laravel migration. I want to change the value to the current time when I press a button. I have tried multiple ways from similar questions but it doesn't seem to work, like using '->update()','->save()', or '->touch()'.
syntax to update in Controller
$check = \DB::table('queueTable')->where('category',$catName2)->where('status','Active')->where('skipped','0')->whereDate('created_at','=',now())->orderBy('queue','ASC')->limit(1);
$counter = \DB::table('queueTable')->where('category',$catName2)->where('status','Inactive')->whereDate('created_at','=',now())->count();
\DB::table('CurrentQueue')->where('id', 2)->update(['DoneQueue' => $counter+1]);
$check->update(['status' => 'Inactive']);
$check->update(['updated_at' => now()->format('Y-m-d H:i:s')]);
my migration
Schema::create('queueTable', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->integer('queue')->default('0');
$table->string('status');
$table->integer('skipped')->default('0');
$table->timestamps();
});
it'd be much appreciated if someone could kindly explain where I'm going wrong.
Thanks in advance.
I want to update the value of "updated_at" to the current time when I press a button

Update you record using Model, it will update "updated_at" automatically.
Change code i your controller:
$check = queueTable::where('category',$catName2)->where('status','Active')->where('skipped','0')->whereDate('created_at','=',now());
$counter = $check->count();
$check = ->orderBy('queue','ASC')->first();
CurrentQueue::where('id', 2)->save(['DoneQueue' => $counter+1]);
$check->save(['status' => 'Inactive']);
Note: If you are not using model, first create Models queueTable, CurrentQueue

Related

Using Laravel 5.5 how do I duplicate a column in a table with a migration?

I would like to duplicate a column on my existing seasons table using a migration in Laravel 5.5.
I can do it using SQL running these two queries:
ALTER TABLE seasons ADD uploader_channel_partner_id BIGINT NULL
then
UPDATE seasons set seasons.uploader_channel_partner_id = seasons.channel_partner_id
I am creating a system where you can transfer the ownership of videos while keeping the original uploader stored.
The up function of my migration currently just has this inside it:
Schema::create('seasons', function (Blueprint $table) {
$table->unsignedBigInteger('uploader_channel_partner_id');
$table->foreign('uploader_channel_partner_id')->references('id')->on('channel_partners');
});
EDIT:
I've made it work with this but it's slow and ugly and I'm sure there is a better way:
public function up()
{
Schema::table('seasons', function (Blueprint $table) {
$table->unsignedBigInteger('uploader_channel_partner_id')->after('channel_partner_id')->nullable();
$table->foreign('uploader_channel_partner_id')->references('id')->on('channel_partners');
});
$seasons = Season::withTrashed()->get();
foreach ($seasons as $key => $season) {
$season->uploader_channel_partner_id = $season->channel_partner_id;
$season->save();
}
}
You can use DB::raw() to force Sql to use another column instead of a string value.
Season::withTrashed()
->update([
'uploader_channel_partner_id' => DB::raw('`channel_partner_id`'),
]);

Laravel 6 - Affiliate Tracking User Registeration

As u guys can see in Image Above, i want to create referral_system that user can register and input referral_user from affiliate users.
And Referral_Code is unique for every user.
My Problem is I cant track Whom that code is.
My User Schema
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('referrer_id')->nullable();
$table->foreign('referrer_id')->references('id')->on('users');
$table->string('referral_code')->unique()->nullable();
$table->string('referred_by')->nullable();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
My User Model
public function referrer()
{
return $this->belongsTo(User::class);
}
public function referrals()
{
return $this->hasMany(User::class);
}
In My UserController
$referrer = User::where('name', auth()->user()->name)->first();
$user = new User();
$user->name = $request->name;
$user->referral_code = substr(uniqid(), 0, 8); // for unique id
$user->email = $request->email;
$user->referrer_id = $referrer ? $referrer->id : null;
$user->role = $request->role;
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'created' => true,
]);
Hope u guys will give me some idea and if u notice mistake in my code, pls correct me, I'll appreciate of all ur help.
Thanks...
I believe you're confusing Laravel relationships. hasOne, belongsTo, etc are not designed to be worked with in the same model. Basically what you're saying in Users model is that "User has a User where user_id = id" which makes no sense.
I have no idea how you've designed your sql tables, I recommend you to split your entities in distinct parts and have pivot tables which binds them: users, affiliates, referrals
- users table have : "id"
- affiliates table have: "id", "refferal_code"
- refferals table have : "id", "affiliate_id", "user_id", "refferal_code"
You tie a user with an affiliate through refferals table, through their IDs.
Then create relationships between those. You may want to read more about Eloquent relationships as well. Hope this answer helps you.

Run Update query in a migration in Laravel 5? [duplicate]

I need to add a new column in my laravel Project, no problem for this, I used the Schema::table() to update and it's ok.
Now I need to find out how many records I have on this table and update with some value.
I have the table Warrants:
Schema::create('warrant_grants', function(Blueprint $table) {
$table->increments('id');
$table->integer('warrant_plan_id');
$table->integer('shareholder_id');
});
So I created the new field with a new migration file:
Schema::table('warrant_grants',function ($table) {
$table->string('name',100);
});
Now I need to update this field name in the table with some values, for example if the table has 100 records, then I need to insert in every row the value "Warrant-X" where X is a number starting with 1 to 100.
For example:
Warrant-1, Warrant-2, ....Warrant-100.
I spent hours looking for some way to do this using Seeds but I didn't found. So basically i have two questions:
Can I use Seeds in Laravel 5 to update values or I can just insert them?
Can I create some SQL inside the Seeds (or migrations) to do this update for me?
Based on this link i found the answer: https://stackoverflow.com/a/23506744/4650792
Schema::table('warrant_grants',function ($table){
$table->string('name',100)->after('id')->nullable();
});
$results = DB::table('warrant_grants')->select('id','name')->get();
$i = 1;
foreach ($results as $result){
DB::table('warrant_grants')
->where('id',$result->id)
->update([
"name" => "Warrant-".$i
]);
$i++;
}
Thanks for the help anyway guys.
Other answers are correct. But note that if you have a lot of records, updating all of them with ORM can take time. Use raw SQL queries to do that faster.
Schema::table('warrant_grants',function ($table){
$table->string('name',100)->after('id')->nullable();
});
DB::raw("UPDATE warrant_grants SET name=name+id");
The SQL query is not exact, and you have to make it for your own DB, but you get the point.
Yes, you can perform updates/inserts/whatever in your migrations. For example:
Schema::table('warrant_grants', function($table) {
$table->string('name', 100);
});
$i = 1;
foreach (WarrantGrants::all() as $warrant_grant) {
$warrant_grant->update([
'name' => 'Warrant-' . $i
]);
$i++;
}
Another possible syntax to achieve this:
DB::table('warrant_grants')
->where('id',$result->id)
->update([
"name" => DB::raw("'Warrant-' + `name`")
]);
This allows the update to be done as one batch rather than iterating over results, and retains most of the familiar Eloquent syntax rather than falling back to just using raw SQL.
The string concatenation syntax may need to be changed depending on the SQL variant used.

Add columns to pivot table in Laravel

I have 4 Models:
Student
Tutor
Course
Admin
I am able to fetch all the students and tutors with their Ids.
I want to the admin to create Courses and store them in pivot Tables:
course_student
course_tutor
Yet, the relationships are not too clear for me. I assume that I need
belongsToMany
between Course and Student. The same goes for Tutor and Course am i right?
What is also not clear is, how can I select many values on the HTML side and submit them to the server.
E.g:
public function store(AdminCreateNewCourseRequest $request)
{
$this->authorize('create-course');
$course = new Course;
$course->name = $request->name;
$course->tutor_id = $request->tutor_id;
$course->student_id = $request->student_id;
$course->spoken_language = $request->spoken_language;
$course->description = $request->description;
$course->save();
What to do?
return redirect($course->path())
->with('flash', 'The course has been published');
}
Here is the AdminCreateNewCourseRequest
public function rules()
{
return [
'name' => 'required|unique:courses|max:60',
'tutor_id' => [
'required',
Rule::exists('tutors', 'id');
],
'student_id' => [
'required',
Rule::exists('students', 'id');
],
'spoken_language' => 'required',
'description' => 'required|max:255'
];
}
I might let the admin selects multiple tutors and students.
How can I accomplish this?
Many Thanks.
As i see, your common model is Course so firstable:
Add in your Course model the following:
public function students()
{
return $this->belongsToMany(Student::class);
}
public function tutors()
{
return $this->belongsToMany(Tutor::class);
}
Then, you need to create the pivot table for both classes ( Student and Tutor ):
Add this to your migrations file (for student and tutor respectively):
Schema::create('course_students', function (Blueprint $table) {
$table->increments('id');
$table->integer('course_id')->unsigned()->index();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->integer('student_id')->unsigned()->index();
$table->foreign('student_id')->references('id')->on('students')->onDelete('cascade');
});
Schema::create('course_tutors', function (Blueprint $table) {
$table->increments('id');
$table->integer('course_id')->unsigned()->index();
$table->foreign('course_id')->references('id')->on('courses')->onDelete('cascade');
$table->integer('tutor_id')->unsigned()->index();
$table->foreign('tutor_id')->references('id')->on('tutors')->onDelete('cascade');
});
Please see the name of fields i am using and be sure you are using the same.
To get the students and tutors of a course you can do it by
$course = App\Course::find($id);
$students = $course->students;
$tutors = $course->tutors;
Hope this help!
By the way this is a very usefull Eloquent Relationships Cheat Sheet you can use to aproach this.

PHP Laravel 5.4.21. Eloquent save insert in first row

I have a problem with saving Eloquent models. For example:
$game = Game::select(['bank', 'state', 'quantity_of_players'])->find($id)->first();
$game->bank += $game->bet;
$game->quantity_of_players++;
$game->save();
As far as i know from documentation, save() should insert changed values in a row with $id, but instead it inserts in a very first row. What's an issue, and how to save it properly to my database in specified row.
Migration for this model:
public function up()
{
Schema::create('games', function (Blueprint $table) {
$table->bigIncrements('id');
$table->enum('state', ['wait', 'search', 'accept', 'play', 'finish']);
$table->smallInteger('quantity_of_players');
$table->smallInteger('ready_players');
$table->smallInteger('finished_players');
$table->integer('bank');
$table->smallInteger('bet');
});
}
Would really appreciate any help with this.
P.S. All SELECT requests works perfectly such as Eloquent create().
The find() method internally calls first(). It's also a good practise to check if the row exists before proceeding. Using findOrFail() does this for you.
$game = Game::findOrFail($id);
$game->bank += $game->bet;
$game->quantity_of_players++;
$game->save();
Edit
If you're insistent on selecting the columns even for the update. Then do this
$game = Game::whereId($id)->first(['bank', 'state', 'quantity_of_players']);
Please try the following
$game = Game::find($id);
$game->bank += $game->bet;
$game->quantity_of_players++;
$game->save();

Categories