I almost finished my website, just one more feature to finish and this is so the user can like just once a post/theme/discussion point(whatever).
I have the table new_theme_user:
1 id
2 id_user(integer)
3 id_theme(integer)
4 upVote(tinyint)
So this is the controller:
class Vote extends Controller {
public function VoteTheme($id, $vote){
$Vote = DB::table('New_Theme_User')->where([
['id_theme', '=', $id],
['id_user', '=', Auth::id()],
])->get(); (1!!!)
if (!isset($vote)) { (2!!!)
if ($vote === 'plus')
DB::table('New_Theme_User')->insert([
['id_theme' => $id, 'id_user' => Auth::id(), 'upVote' => 1],
]);
else
DB::table('New_Theme_User')->insert([
['id_theme' => $id, 'id_user' => Auth::id(), 'upVote' => 0],
]);
if ($vote === 'plus') {
DB::table('New_Themes')
->where('id', $id)
->increment('upVotes', 1);
} else {
DB::table('New_Themes')
->where('id', $id)
->increment('downVotes', 1);
}
}
$Themes = NewTheme::paginate(5);
return redirect()->route('welcome', ['Themes'=>$Themes]);
}
};
1!!! - Is the select query which creates an object(in order to find in database if someone has already voted before the theme/post which he wants to vote again.
2!!! - Is the if statement, if the object doesn't have the values - this means the user can vote once so it populates the DB with information.
The problem: I can't figure how to work around the (2!!!), I tried isset, empty, whatever else I could find on internet, it doesn't work, even if the user voted once more the if goes through and it seems I can't find a solution. Every given help, I will greatly appreciate. Thank you!
NewThemeUser model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class NewThemeUser extends Model
{
protected $table = 'new_theme_user';
}
Now in controller you can do like this
App\NewThemeUser::firstOrCreate(['id_theme' => $id, 'id_user' => Auth::id()])->increment($upVotes ? 'upVotes' : 'downVotes');//This will fetch the first record if there any exists for the user then increment if $upVotes then the column to increment is upVotes else upVotes
Related
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
]
I want from the DB class to switch to Eloquent and I have a few of queries
This is first, I want to insert in subscription_user user_id of user and hard core subscription_id = 1 as default.
DB::table('subscription_user')->insert(
['user_id' => $user->id, 'subscription_id' => 1]
);
Second, I want to return verification token
$check = DB::table('user_verifications')->where('token',
$verification_code)->first();
Third, I want to update accepted field
$res = DB::table('offers')
->where('id', $id)
->update(['accepted' => 1]);
#1
DB::table('subscription_user')->insert(
['user_id' => $user->id, 'subscription_id' => 1]
);
Eloquent equivalent (*):
$subscriptionUser = SubscriptionUser
::create(['user_id' => $user->id, 'subscription_id' => 1]);
In case this comes from a many-to-many relationship between the models Subscription and User you could just do (**):
Subscription::find(1)->users()->attach($user->id);
#2
$check = DB::table('user_verifications')->where('token',
$verification_code)->first();
Eloquent equivalent (***):
$check = UserVerification::where('token', $verification_code)->first();
#3
$res = DB::table('offers')
->where('id', $id)
->update(['accepted' => 1]);
Eloquent equivalent:
$res = Offer::find($id)->update(['accepted' => 1]); // this will return a boolean.
$offer = Offer::find($id); // this will get the updated record.
(*) In order for this to work you need a Eloquent model called SubscriptionUser with the table property set to: 'subscription_user'.
(**) In order for this to work you need to set the relationship in the models.
(***) In order for this to work you need a Eloquent model called UserVerification with the table property set to: 'user_verifications'.
I have column named flag and I want to update it if value is 1 to null and if value is null to 1 so far is easy to update this column but issue comes where I send multiple data to controller and not only one.
code
public function flagmultiplemessage(Request $request){
$ids = $request->input('ids');
DB::table('messages')->whereIn('id', $ids)
->whereNotNull('messages.flag')->update(['flag' => null])
->whereNull('messages.flag')->update(['flag' => '1']);
}
with function above i get:
message Call to a member function whereNull() on integer
dd
code above is something like this:
ids = [11, 12, 3]
database = [
11->flag = 1,
12->flag = null,
3->flag = 1,
]
the result of code above most change my database like:
database = [
11->flag = null,
12->flag = 1,
3->flag = null,
]
any idea why i get error?
it occurred because you called whereNull method on update method.
You should run 3 separate query like this.
public function flagmultiplemessage(Request $request){
$ids = $request->input('ids');
DB::transaction(function () use ($ids) {
DB::table('messages')->whereIn('id', $ids)
->whereNotNull('messages.flag')->update(['flag' => 0]);
DB::table('messages')->whereIn('id', $ids)
->whereNull('messages.flag')->update(['flag' => 1]);
DB::table('messages')->whereIn('id', $ids)
->where('messages.flag', 0)->update(['flag' => null]);
});
}
but for better performance I suggest you use boolean for flag column and use this simple query
DB::table('messages')->whereIn('id', $ids)->update(['flag' => DB::raw('!flag')]);
The main reason for the error is that the update() method is not chainable
Alternatively, You can do the update in one query by using the mysql Case statement.
public function flagmultiplemessage(Request $request) {
$ids = $request->input('ids');
DB::table('messages')->whereIn('id', $ids)
->update(['flag' => DB::raw('case when flag is null then 1 else null end') ]);
}
You can do this
DB::table('messages')->whereIn('id', $ids)->where(function ($query) {
$query->whereNotNull('messages.flag')->update(['flag' => null])
->orWhereNull('messages.flag')->update(['flag' => '1']);
})
please help me. I want to ask:
Let say I have 2 tables: user_master and people.
Now I am currently build an application in PHP with Laravel 5.1 framework that select the data from user_master table (with some constraint in where clause) and insert into people table.
The code is :
public function handle() {
$results = DB::select(DB::raw("SELECT * FROM user_master WHERE div_id = 1"));
foreach ($results as $res) {
//saving to array
//insert query to table people here.
}
}
My questions are:
How to save the result of select query to array, and
Insert that array into people table using RAW query (INSERT INTO people VALUES (...)).
P.S.: My query is RAW query, not using Eloquent. And please provide answer without Eloquent.
Thank you so much for any answer.
I have done the same scenario like this
$users=DB::table('Users')->where('created_at' ,'>=','2016-09-06')->get();
foreach ($users as $user){
DB::table('users_report')->insert(
array(
'id' => $user->id,
'username' => $user->username,
'lastname' => $user->lastname,
'email' => $user->email,
'created_at' => $user->created_at,
'updated_at' => $user->updated_at,
)
);
}
change your like according to your logic , its works 100% perfectly..
I think that is right
$results = DB::table('user_master')->where('div_id', 1)->get();
if your table and master have the same strucure, you just set the primary key in the below code. If they are not in the same structure, you have to ajust the results to the structure of the people bfore you insert to peopel table.
hope it will helps.
function delete_col(&$array, $offset) {
return array_walk($array, function (&$v) use ($offset) {
unset($v[$offset]);
});
}
public function handle() {
$results = DB::table('user_master')->where('div_id', 1)->get();
delete_col($results, $premiarykeyOfuser_master);
DB::table('people')->insert($results);
}
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.