Laravel Eloquent for Social Network - laravel

I'm building a social network. I have Users and Posts. for like concept I created a table (Likes):
_______________________
|id | post_id | user_id |
| | | |
I want to show people who like a post below each post.
so I need to save a row for each Like
.
My problem is Eloquent and how to save a Like row
$post = Post::find($request->postId);
$like = new Likes();
$user = $request->user();
$post->likes()->save($like, $user);
return 'done';
this code set user_id (Likes tabel) 0
is there a better way for Like Concept?

in your controller use this method :
public function postLikePost(Request $request)
{
$post_id = $request['postId'];
$is_like = $request['isLike'] === 'true' ? true:false;
$update = false;
$post = Post::find($post_id);
if(!$post){
return null;
}
$user = Auth::user();
$like = $user->likes()->where('post_id',$post_id)->first();
if($like){
$liked = $like->likes;
$update = true;
if($liked == $is_like)
{
$like->delete();
return null;
}
} else
{
$like = new Like();
//die($like);
}
$like->likes = $is_like;
$like->user_id = $user->id;
$like->post_id = $post->id;
if($update){
$like->update();
}
else{
$like->save();
}
return null;
}

Related

Customize Laravel 8 Passport methods

The login validation I use is not Laravel's default. How do I customize Passport methods?
The following code I use to validate with web middleware.
$username = $request->username;
$password = strtoupper(md5($request->password));
$system = env("CODE_SYSTEM", 12);
$sql = "SELECT user.validate( '$system' , '$username', '$password')";
$stmt = DB::select(DB::raw($sql));
$result = $stmt[0]->validation;
if ($result == "ok") {
$user = new User();
$id = DB::table('users')->select('id')
->where('username' , $username)->first();
$user = User::find($id->id);
return $user;
}
To customize you need add the validateForPassportPasswordGrant() at User method, example:
public function validateForPassportPasswordGrant($password)
{
$password = strtoupper(md5($request->password));
$system = env("CODE_SYSTEM", 12);
$sql = "SELECT user.validate( '$system' , '$this->username', '$password')";
$stmt = DB::select(DB::raw($sql));
$result = $stmt[0]->validation;
if ($result == "ok") {
return true;
}
return false;
}
If you need to change the user column name where the passport search username:
public function findForPassport($username)
{
return $this->where('the_username_column', $username)->first();
}

For loop request Laravel

Just a quick question guys really thankful for everyone who can help.
How do I foreach loop inside create eloquent in laravel
Here is my code. I'm trying to get and match the answers for their respective survey questions
public function answer_survey(Request $request, $id)
{
$userId = Auth::user()->id;
$user = User::where('id', $userId)->first();
$userNectarPoint = UserNectarPoint::where('user_id', $userId)->first();
$survey = Survey::find($id);
$survey_questions = SurveyQuestion::where('survey_id', $survey->id)->get();
$current_nectarpt_value = $userNectarPoint->nectar_points;
$questionIds = $request->id;
$questions = $request->question;
$answers = $request->answer;
foreach ($answers as $answer) {
}
foreach ($survey_questions as $survey_question) {
$userAnsweredSurvey = new UserAnsweredSurvey;
$userAnsweredSurvey->user_id = $userId;
$userAnsweredSurvey->user_fullname = $user->first_name . ' ' . $user->middle_initial . ' ' . $user->family_name;
$userAnsweredSurvey->survey_id = $survey->id;
$userAnsweredSurvey->survey_title = $survey->title;
$userAnsweredSurvey->survey_question_id = $survey_question->id;
$userAnsweredSurvey->survey_question = $survey_question->question;
$userAnsweredSurvey->answer = $answer;
$userAnsweredSurvey->save();
}
$result_nectarpt = $current_nectarpt_value + $survey->reward_points;
$userNectarPoint->nectar_points = $result_nectarpt;
$userNectarPoint->save();
return back()->with('status', 'survey_done');
}

How to send notices to members who have different membership roles?

Immediately, I want to ask as I asked in the title.
I Have controller like this:
public function store(Request $request)
{
//
$this->validate($request, [
'status'=> 'required|min:1|max:2',
'subject' => 'required|min:10|max:255',
'body' => 'required|min:10|max:100000'
]);
if ($request->status == 1){
$this->validate($request, [
'email' => 'required|email',
]);
$user = User::whereEmail($request->email)->firstOrFail();
$notice = new Notice();
$notice->user_id = $user->id;
$notice->title = $request->subject;
$notice->priority = $request->priority;
$notice->body = $request->body;
$notice->status = 0;
if ($request->hasFile('featured')){
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$notice->file = 'uploads/posts/'. $featured_new_name;
}
$notice->save();
session()->flash('message', "Send Message to ".$user->name." Successful!");
Session::flash('type', 'success');
Session::flash('title', 'Message Send Success!');
return redirect()->route('adminMessage.create');
}
else {
$users = User::all();
if ($request->hasFile('featured')){
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$attachment = 'uploads/posts/'. $featured_new_name;
}
foreach ($users as $user){
$notice = new Notice();
$notice->user_id = $user->id;
$notice->title = $request->subject;
$notice->priority = $request->priority;
$notice->body = $request->body;
$notice->status = 0;
if ($request->hasFile('featured')){
$notice->file = $attachment;
}
$notice->save();
}
session()->flash('message', "Send Message to all Users Successful!");
Session::flash('type', 'success');
Session::flash('title', 'Message Send Success!');
return redirect()->route('adminMessage.create');
}
}
I Have 2 status in this field:
For Status 1, I send for selected member (Only One)
For Status 2, I send for all User use $user= User::all();
So I need for help with Send Notice with Membership_role
I Have Memberships Tables, for example like this:
=========================
| id | name | count |
-------------------------
| 1 | free | 200 |
| 2 | free | 200 |
| 3 | free | 200 |
| 4 | free | 200 |
How do I send a message to Membership Id: 2,3,4
If it is a property at the User model, you can use querys to find the user or users you want.
/*
I use a switch just in case you have more than 2 notice statuses to handle
the sendTo functions are functions declared in your controller to handle the cases.
*/
switch($notice->status){
/*Query the user by the membership id to send the notice*/
case 1:
$user = User::where('membership_id',$the_membership)->first();
return $this->sendTo($user);
case 2:
/*Get all users*/
$users = User::all();
return $this->sendTo($users);
/*Handle other notice statuses*/
default:
return $this->sendToDefault();
}

Laravel : how to use pivot table for taggable system

I want create tag for posts
for example I created three new tags but submit a only a row in TaggablesTable
Tags Table:
id | name |
--------------
1 | first|
2 | two |
3 | three|
taggables Table:
tag_id|taggable_id|taggable_type
-------------------------------
3 | 1 |post
public function store(Request $request)
{
$data = $request->all();
$post = Post::create($data);
if ($post && $post instanceof Post) {
$tags = $request->input('tags');
foreach ($tags as $tag){
$newTag =Tag::firstOrCreate(['name'=>$tag]);
$tags= $newTag->id;
}
$post->tags()->sync($tags);
return redirect()->back();
}
}
How can it be done?
You are overwriting tags every time the loop runs. Map seems like an easier approach to your problem.
$data = $request->all();
$post = Post::create($data);
$tags = collect($request->input('tags'))->map(function (string $tag) {
return Tag::firstOrCreate(['name'=>$tag])->id;
})->all();
$post->tags()->sync($tags);
return redirect()->back();

update multiple rows after insert in codeigniter

After insert I want to update field with ($id.'mytext') where in db that field is empty for all rows.
table name: peca
columns:
id -autoincrement
A -varchar user insert
CB -varchar auto insert with update
MODEL WILL RETURN ALL ROWS WHERE CB=empty
function model1() {
$this->db->select('*');
$this->db->from('peca');
$this->db->where('CB', '');
//$this->db->where('id', $fileid);
$query = $this->db->get();
if ($query) {
return $query->result();
} else {
return false;
}
}
MODEL WILL update in db where CB=empty
function model2($dados = NULL) {
if ($dados !== NULL) {
// extract($dados);
$this->db->where('CB', '');
$this->db->update('peca', $dados);
return true;
} else {
return false;
}
}
CONTROLLER
$this->load->model('model_peca');
$resultadocadastropeca = $this->model_peca->model1($id);
$data = 'id' => $id;
$appointment = array('codigoean' => $data.'.PECA.');
$appointment = $this->model_peca->model2($appointment);
START TABLE
Previous values inserted from import so CB can only be generated after id exists
id|CB |
22| |
31| |
RESULTS
I'm changing CB to .PECA. in all rows where CB=empty but $id for each row is not passing
id|CB |
22|.PECA.|
31|.PECA.|
EXPECTED
id|CB |
22|22.PECA.|
31|31.PECA.|
I still don't fully understand what you want to do, but if you want to fetch something where a column is empty or null:
$this->db->where("WHERE yourColumn IS NULL OR yourColumn = ''");
As per your revised question, this should work:
$this->db->select('id');
$this->db->where('CB', '');
$q = $this->db->get('peca');
if ($q->num_rows() == 0) {
die('nothing to do here');
}
$res = $q->result();
foreach ($res as $item) {
$data[] = array('id' => $item->id, 'CB' => $item->id . '.PECA.');
}
$this->db->update_batch('peca', $data, 'id');

Resources