Laravel:: reuse article id into new table - php

I need to be able to make a "like" system. I have three tables. Users, Articles, Likes.
In the Articles table I have the id, title, body. In Likes I have id, user_id, and article_id.
So when a person presses like on the article I fill the table with their user id and the article_id.
However I'm running into the problem of adding the id. This is basic to most I know, I have seen the laravel videos but its still new to me.
Here is what I have in the article controller.
$article = new Article();
$article->body = 'new article body';
$article->title = 'new article Title';
$article->type = 'fashion';
$article->save();
$articles = Article::where('type', 'fashion')->get();
//$articles = Article::all();
return view('articles.index', compact('articles'));
public function store()
{
$request = Request::all();
$likes = new like();
$likes ->article_id = Article::find($id);
$likes->user_id = Auth::user()->id;
$name = Auth::user()->name;
$likes->save();
$followers = new Follower();
$followers->follower_id = Auth::user()->id;
$followers->user_id = $request['user_id'];
$name = Auth::user()->name;
$followers->save();
return redirect('article');
}

You are trying to use a variable which doesn't exist. Variable $id being used on this line
$likes ->article_id = Article::find($id);
is not initialized anywhere. Maybe you are expecting it to be on the Request? So in that case, $request->id in that case.
Also if your model is called Like than you should fix the case on this line $likes = new like(); to $likes = new Like();.

Related

An Update in Laravel Framework is returning A new Record

I am new to PHP and Laravel. I have learned much, but I am having a problem seeing my error in what should be a simple task.
I have a form which is populated from data in a MySQL database. When I submit it, it creates a new record instead of updating the existing record. This is the form action that I am using:
<form action="{{route('updateAlert', $alert->id)}}" method="post" name="saveAlert" id="saveAlert" class="needs-validation"
#csrf
#method("PUT")
///form fields here
</form>
Here are the two related routes. editAlert brings you to the form above. updateAlert is supposed to bring you to the update method on my AlertController.
Route::get('/alerts/edit/{id}', 'AlertController#edit')->name('editAlert');
Route::put('/alerts/edit/{id}', 'AlertController#update')->name('updateAlert');
Here is what my AlertController looks like:
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Alert $alert)
{
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
return redirect()->route('viewAlerts')->with('success', 'Your alert has been updated.');
}
What am I missing? I have the same basic code in another section of the app that is working as expected. Thanks in advance.
You Are Not Fetching your row id. You need to use model and pass your id to your model to update any specific row.
Ex.
I the model name just pass your model name.
public function update(Request $request, Alert $alert)
{
$alert = ModelName::find($alert);
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
return redirect()->route('viewAlerts')->with('success', 'Your alert has been updated.');
}
To update things in Laravel, you need a query builder object; Alert $alert returns an object of the model, so it can not be used to update things.
Note: find method is a special method whose objects can be used to update records, unlike the "first" method.
So your code must be changed to:
public function update(Request $request, Alert $alert)
{
$alert = Alert::where('id', $alert->id); // or: Alert::find($alert->id);
$alert->type = $request->type;
$alert->title = $request->title;
$alert->body = $request->body;
$alert->link = $request->link;
$alert->eff_dt = Carbon::parse($request->eff_dt);
$alert->exp_dt = Carbon::parse($request->exp_dt);
$alert->note = $request->note;
$alert->user_id = auth()->user()->id;
$alert->save();
}

How to pass array in db using laravel 7

I'm trying array data send in db but I got error
here is my function where i send data in db
public function create(Request $request)
{
$tags = explode(",", $request->labels);
$posts = new Post();
$posts->user_id = $request->id;
$posts->title = $request->title;
$posts->description = $request->description;
$tags = explode(",", $request->labels);
$posts->tags = $tags; // error is here in this line
$posts->save();
return redirect()->back()->with('message' , 'post created!!!!!');
}
If $posts->tags is related - i.e Post hasMany Tag, Tag belongsToMany Post - then you should be able to attach the tags to the post like so:
$posts->tags()->attach($tags);
$posts->save();

get user id when created a new posts

i wanted to retrieve id from Users Table for user_id field in Posts table
i've already tried with Auth::id(); but its retrieving current authenticated Id
so what i wanted is, when i created new data, the id from Users to be displayed at user_id Field in Posts Table
This is my Post model:
public function user()
{
return $this->belongsTo(User::class);
}
This is my User Model:
public function posts()
{
return $this->hasMany(post::class);
}
and this is how i currently stored my data:
$post = new post;
// $post->parent_id = $request->input('id');
$post->user_id = Auth::id();
$post->type = $request->input('type');
$post->slug = str_slug($request->input('title'));
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->excerpt = $request->input('excerpt');
$post->image = $imageName;
$post->tag = $request->input('tag');
$post->metas = $request->input('metas');
$post->ispublished = $request->input('ispublished');
$post->published_at = $request->input('published_at');
$post->save();
how do i exactly do what i want?
// edited
i'm new to this so i got my questions all wrong,
i already got what i want by using Auth::id.
i just wanted to record the id of the creator of the posts
your question isn't clear exactly, but you can use relationship to this work like :
$user->post()->create([
$post->type = $request->input('type');
$post->slug = str_slug($request->input('title'));
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->excerpt = $request->input('excerpt');
$post->image = $imageName;
$post->tag = $request->input('tag');
$post->metas = $request->input('metas');
$post->ispublished = $request->input('ispublished');
$post->published_at = $request->input('published_at');
]);
This solution isn't really good in terms of performance because it uses join.
Check your routes to the controller if it has middleware. To retrieve user data through Auth middleware is required.
Example
Route::post('/', 'PostController#store')->middleware('auth:users');

groupBy only gets the first id

I have a many to many relationship between departments and users my pivot table is department_user. I wanted to select all the department_name depending of the user's department using groupBy method to merge all the department_name into one. See below my statement.
$departmentRecipient = DB::table('users')->select('departments.department_name', 'users.id')
->join('department_user', 'users.id', '=', 'department_user.user_id')
->join('departments', 'department_user.department_id', '=', 'departments.id')
->groupBy('departments.department_name')
->get();
Result using die and dump.
As you can see here I have an id of 4 under "Department of Engineering". My main problem is it doesn't fetch all the id under "Department of Engineering". But in my SQL I have id of 5 not only 4. How can I solve this problem? Any help would greatly appreciated. Please see result below.
Output:
This is the output of my list. I wanted to get all the users id belongs to the specific option for the user. But if I choose "Department of Engineering" it only gets the id of 4 not 5. I wanted to get 4 and 5 once.
Controlller:
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
return view ('document.create')->with('departmentRecipient', $departmentRecipient);
}
public function postDocuments(Request $request)
{
$this->validate($request,
[
'title' => 'required|regex:/(^[A-Za-z0-9 ]+$)+/|max:255',
'content' => 'required',
'category' => 'required',
'recipient' => 'required',
]);
$document = new Document();
//Request in the form
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$document->save();
$user = Auth::user();
foreach($request->recipient as $recipientId)
{
$document->sentToUsers()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
}
Model
User
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Department
public function users()
{
return $this->belongsToMany('\App\Models\User', 'department_user');
}
View
<div class = "form-group">
<label for = "recipient" class = "control-label">Recipient:</label>
<select name = "recipient[]" multiple class = "form-control select2-multi" id = "myUserList">
#foreach ($departmentRecipient as $list)
<option value = "{{ $list->id }}">{{ $list->department_name }}</option>
#endforeach
</select>
</div>
From your given code it seems you are not using Eloquent ORM, you are doing it using Query Builder.
If you don't have a performance concern right now you can do it using separate queries. Like-
$departmentRecipient = DB::table('departments')->all();
foreach($departmentRecipient as $department){
$department->users = DB::table('department_user')->where('department_id',$department->id)->pluck('user_id');
}
But the better way is to use the eloquent with relationships. Define the many to many relationship in your eloquent model of Users and Departments (assuming you have eloquent model for them). You will find details about eloquent relationships at laravel documentation.
Update:
From the update of your post it is actually pretty easy to do what you want. If your Request contains the selected department id then you can do the following:
public function postDocuments(Request $request)
{
$document = new Document();
$document->title = $request->title;
$document->content = $request->content;
$document->category_id = $request->category;
$document->save();
//get the users list of the selected department id
$selected_department = $request->department_id; //this must be included in your POST data
$users = DB::table('department_user')->where('department_id',$selected_department)->pluck('user_id');
//now you have the list of the users id
foreach($users as $user){
// do what you need here
}
}
Update 2:
Following controller code might work for you.
Controller:
public function getDocuments()
{
// I am suggesting here to change the '$departmentRecipient' to '$departmentlist', as it is more meaningful. Also in your view
$departmentlist = DB::table('departments')->get();
return view ('document.create')->with('departmentlist', $departmentlist);
}
public function postDocuments(Request $request)
{
//same as you have till the $document->save()
....
....
//then do this
$recipients = array();
$departments = $request->recipient;
foreach($departments as $department){
$users = DB::table('department_user')->where('department_id',$department)->pluck('user_id');
$recipients = array_merge($recipients, $users);
}
//now you have a complete list of the users from selected departments
//Do as you intend to like this
$user = Auth::user();
foreach($recipients as $recipientId)
{
$document->sentToUsers()->sync([ $recipientId => ['sender_id' => $user->id]],false );
}
}

Pagination using Doctrine and ZF2

i am trying to implement Pagination Using ZF2 and Doctrine.
What i am trying to do here is to fetch data from An associated table lets say 'xyz'.
Where as my categories table is doing one to many self referencing on its own PK.
MY catgories tables has following feilds
ID (PK)
Created_at
Category_id (self referencing PK)
My XYZ table lets say it is called Name table has
ID (PK)
Category_id(FK)
name
Detail
This is what i am trying to do to fetch data
public function allSubcategories($id, $column, $order) {
$repository = $this->entityManager->getRepository('Category\Entity\Category');
$queryBuilder = $repository->createQueryBuilder('category');
$queryBuilder->distinct();
$queryBuilder->select('category');
$queryBuilder->join('Category\Entity\CategoryName', 'category_name', 'WITH', 'category.id = category_name.category');
$queryBuilder->orderBy("category.status");
$q = $queryBuilder->getDql();
return $query = $this->entityManager->createQuery($q);
}
And in my controller this is what i am doing
public function subcategoryAction() {
///////////////////////////InPut Params Given for the pagination
$category_id = (int) $this->params()->fromRoute('id', 0);
$page = (int) $this->params()->fromRoute('page', 0);
$column = $this->params()->fromQuery('column');
$order = $this->params()->fromQuery('order');
$categoryModel = $this->getServiceLocator()->get('Category');
$categoryModel->category = $category_id;
$perPage = 10;
$request = $this->getRequest();
if ($request->isGet()) {
$view = new ViewModel();
$query = $categoryModel->allSubcategories($category_id, $column, $order);
$paginator = new ORMPaginator($query);
$paginator = new \Zend\Paginator\Paginator(new
\Zend\Paginator\Adapter\ArrayAdapter(array($paginator)));
$paginator->setCurrentPageNumber($page);
$paginator->setItemCountPerPage(2);
}
return array('id' => $category_id, 'view' => $paginator);
}
Now i am not getting results with pagination implemented can some 1 guide me about what i am missing?
You are using the wrong paginator there. Instead, you can use the one by DoctrineORMModule ( see DoctrineORMModule\Paginator\Adapter\DoctrinePaginator).
It may not be very obvious, but the logic is similar to what you already wrote:
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as PaginatorAdapter;
use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator;
use Zend\Paginator\Paginator as ZendPaginator;
$query = $categoryModel->allSubcategories($category_id, $column, $order);
$paginator = new ZendPaginator(new PaginatorAdapter(new ORMPaginator($query)));

Categories