storing id in the immediary table (latest not found) - php

I have many to many relationships between posts and tags
The problem is when I want to get the post id and the tag id to link them in their immediary table I did a simple query to do that and I used latest() method in laravel query builder and it threw this error:
Method Illuminate\Support\Collection::latest does not exist.
This is my store function:
public function store(Request $request)
{
{
$this->validate($request,[
'title'=>'required',
'body'=>'required',
'tags'=>'required',
'slug'=>'required',
]);
$input = $request->all();
$tags = explode(",", $request->tags);
if ($input != null) {
$post = post::create($input);
$post->tag($tags);
// the problem is in this two lines
$post_id = DB::table('posts')->pluck('id')->latest();
$tagged_id = DB::table('tagging_tagged')->pluck('id')->latest();
//
dd($tagged_id , $post_id);
$relationship = new post_tagged;
$relationship->post_id = $post_id;
$relationship->tagged_id = $tagged_id;
$relationship->save();
return redirect('/admin/blog')->with('success' , 'Post added successfully');
}
return redirect('/admin/blog');
}
}
the idea that I want to achieve with those two lines is to get the latest id in the post table and in the tags table (which is the newest post)
and then storing it in the immediary table
I solved the problem by doing this
store function
public function store(Request $request)
{
{
$this->validate($request,[
'title'=>'required',
'body'=>'required',
'tags'=>'required',
'slug'=>'required',
]);
$input = $request->all();
$tags = explode(",", $request->tags);
if ($input != null) {
$post = post::create($input);
$post->tag($tags);
$post_id = DB::table('tagging_tagged')->latest('taggable_id')->first();
$post_id = $post_id->taggable_id;
$tagged_id = DB::table('tagging_tagged')->latest('id')->first();
$tagged_id = $tagged_id->id;
$relationship = new post_tagged;
$relationship->post_id = $post_id;
$relationship->tagged_id = $tagged_id;
$relationship->save();
return redirect('/admin/blog')->with('success' , 'Post added successfully');
}
return redirect('/admin/blog');
}

Related

Laravel edit orders as user

I create order system in Laravel, I can add new order as user and I can display all order as admin user. I have only problem with edit this order as user.
This is my controller
public function index(){
$orders = Orders::with('category', 'type')->where('user_id', auth()->user()->id)->orderBy('id', 'desc')->paginate(6);
return view('account.orders', compact('orders'));
}
public function store(Request $request) {
$order = new Orders;
$order->user_id = auth()->user()->id;
$order->category_id = $request->input('category_id');
$order->type_id = $request->input('type_id');
$order->name = $request->input('name');
$order->description = $request->input('description');
$order->price = $request->input('price');
$order->save();
return back()->with([
'status'=> [
'type'=>'success',
'content'=>'Zmiany zostaƂy zapisane',
]
]);
}
public function edit(Orders $order_id){
$categories = Categories::get();
$types = OrdersCategories::get();
$order = Orders::where('user_id', auth()->user()->id)->findOrFail($order_id);
return dd($order_id);
}
When I click edit in user dashboard not show data from database.
Try This,in your controller edit function.
try {
$categories = Categories::get();
$types = OrdersCategories::get();
$order = Orders::where('user_id', auth()->user()->id)
->findOrFail($order_id);
return redirect()->action('Admin\OrderController#index');
} catch (\Exception $exception) {
return back()->withError($exception->getMessage())->withInput();
}
Because your model is called Orders. You should be using /{orders}/ instead of /{order}/ in your routes if you want to make use of route-model binding.
Change the route to Route::get('/{orders}/edit', 'OrderController#edit')->name('edit');

Laravel 5.7 add comments to database

I am following tutorial for creating forum in Laravel and I am currently at posts replies so I can add them to the database.
I have this function in ForumController.php
public function postReply(CreateReplyRequest $request) {
$post = Post::where('slug', '=', $request['slug'])->first();
if( $post ) {
$reply = new Reply;
$reply->post_id = $post->id;
$reply->user_id = Auth::user()->id;
$reply->text = $request['text'];
$reply->save();
return redirect()->back();
}
return redirect('/');
}
It is only returning me back to homepage (/) and not adding any reply to database. I do not know where can be error. Thanks for help.
Try this:
public function postReply(CreateReplyRequest $request) {
$post = Post::where('slug', $request['slug'])->first();
if( $post != null) {
$reply = new Reply;
$reply->post_id = $post->id;
$reply->user_id = Auth::user()->id;
$reply->text = $request['text'];
$reply->save();
return redirect()->back();
}
}
Thanks for answers. I had to install Form package from Laravel Collective via Composer. I had to pass the slug via {!! Form::hidden('slug', $post->slug) !!}. Thanks for help.

Limit Comment in Post Laravel

So this is the problem, I have application with post and comment. But I want to limit the comment per user, So if there is 1 post only 1 comment per user. Is it possible ?
Here is my store function in CommentController:
public function store(Request $request, $post)
{
$this->validate($request, array(
'title' => 'required|max:200',
'desc' => 'required|max:800'
));
$comments = new Comment();
$comments->id_user = Auth::id();
$comments->id_post = $post;
$comments->title = $request->A;
$comments->desc = $request->B;
$comments->save();
return redirect()->route('controller.index');
}
What query can I add in this store function to limit the user to only comment once in 1 post. Thanks guys hope you can help me.
It's very simple you need to check if a comment for a user and post already exists like this:
if (! Comment::where('id_user', $userId)->where('id_post', $postId)->exists()) {
//save the comment
} else {
// do not save the comment
}
In your case $userId may be Auth::user()->id, and the $postId is $post->id.
You should try this
Check comment added for this post by this user
$result = DB::table('comments')->where('id_user', '=', Auth::id())->where('id_post', '=', $incase->id)->get();
if(count($result) < 1){
$comments = new Comment();
$comments->id_user = Auth::id();
$incase = Incase::find($id);
$comments->id_post = $incase->id;
$comments->title = $request->A;
$comments->desc = $request->B;
$comments->save();
return redirect()->route('controller.index');
}
else{
return redirect()->route('controller.index')->with('warning','Already Commented');
}
OR
Hide Comment box for that user if one comment stored

Laravel - Update dynamic fields in relationship table

I have two tables Cars and Features, where Cars and Features have one to many relations.
Cars table has ID, Name columns. Features tables has ID, CarID, Name, Feat Image.
When I update the details, Cars table updated Features table is not updated.
Cars.php
public function features() {
return $this->hasMany(Features::class, 'cars_id');
}
Features.php
public function feat()
{
return $this->belongsTo(Cars::class, 'cars_id');
}
Controller.php
Update Method
public function update(Request $request, $id)
{
$requestData = $request->all();
$cars = Cars::findOrFail($id);
$features = Features::with(['feat'])->where('cars_id', $cars->id)->get();
if($cars->update($requestData))
{
if ($request->hasFile('feat_img'))
{
$file = $request->file('feat_img');
$rules = array('file' => 'required|mimes:png,gif,jpeg');
$validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$name = $request->name;
for ($i=0; $i < count(request('name')); ++$i)
{
$features->name = request('name')[$i];
$feat_img_name = uniqid() . '.' . $images[$i]->getClientOriginalExtension();
$images[$i]->move(public_path('/images/'), $feat_img_name);
$features->feat_img = '/images/'.$feat_img_name;
}
}
}
$cars->features()->update($features);
session()->flash('message', 'Product updated successfully.');
return redirect('/');
}
Store Method
public function store(Request $request, Cars $cars)
{
$cars= new Cars;
$cars->name= request('name');
$cars->image= $image;
if($cars->save())
{
$features= [];
$images = $request->file('feat_img');
$name = $request->name;
for ($i=0; $i < count(request('name')); ++$i)
{
$features= new Features;
$features->name = request('name')[$i];
$feat_img_name = uniqid() . '.' . $images[$i]->getClientOriginalExtension();
$images[$i]->move(public_path('/images/'), $feat_img_name);
$features->feat_img = '/images/'.$feat_img_name;
$cars->features()->save($features);
}
session()->flash('message','Product successfully added.');
return redirect ('/');
}
}
Use update like this :
$features=Features::findOrFail(id);
$features->field=$value;
$features->save();
Hope this works.

Symfony2 - Populate text field with ArrayCollection?

I am using the FPNTagBundle and I would like to have a text field to add tags to entities that works in the same way as the one on this site.
I can create a new entity with tags no problem by using explode but when I come to edit the entity again, I get something like this in the text field.
Doctrine\Common\Collections\ArrayCollection#0000000062a07bb50000000047044868
Is there a way I can pre populate a text field with the array collection, so that all of the tags appear, separated by a space?
Here's what I currently have in my controller:
public function editpageAction(Request $request, $id = NULL)
{
$em = $this->getDoctrine()->getEntityManager();
$tagManager = $this->get('fpn_tag.tag_manager');
$page = new Page();
if ( ! empty($id))
{
$page = $em->getRepository('ContentBundle:Page')->findOneById($id);
$tagManager->loadTagging($page);
}
$form = $this->createForm(new PageType(), $page);
if ($request->isMethod('POST'))
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($page);
$em->flush();
return $this->redirect($this->generateUrl('content_admin_list_sections'));
}
}
return $this->render('ContentBundle:Admin:page.html.twig', array('form' => $form->createView()));
}
Any advice appreciated.
Thanks
This is what the Data transfomers are made for.
How to use Data Transformers
A simple example:
public function transform($tags)
{
$tags = $tags->toArray();
if (count($tags) < 1)
return '';
else
return implode(' ', $tags);
}
public function reverseTransform($string)
{
$tags = new ArrayCollection();
$tagsArray = explode(' ', $string);
if (count($tagsArray) > 0)
$tags = new ArrayCollection($tagsArray);
return $tags;
}

Categories