get user id when created a new posts - php

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');

Related

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();

Laravel Model not returning properties with default value after creation

In my controller after I create a new Post I return the new post in a post variable. For some reason I don't get the properties with default values back. I noticed that if I set the value to something in controller it does indeed return the properties in the payload.
public function create(Request $request)
{
$validatedData = $request->validate(PostValidator::$create);
$post = new Post();
$post->postcategory_id = $request->input('postcategoryid');
$post->user_id = $request->input('authorid');
$post->thumbnail = $this->uploadFile($request, 'thumbnail', config('app.defaultImage'));
$post->video = $request->input('video');
$post->slug = $this->slugify($request->input('title'));
$post->url = '/publicaciones/'.$this->slugify($request->input('title'));
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->isVisible = false; //IF I DO THIS isVisible is returned in $post variable
$post->save();
$post->load(['postcategory','author']);
return response()->json([
'post' => $post,
]);
}
you can say laravel works like that. default values defined in the database layer is absent in a newly created object. however you can use refresh to refresh the object before returning. and it will have the missing values then.
$post = new Post();
$post->attribute = $request->attribute;
$post->save();
$post = $post->refresh();
return $post;
or you can set default values in the model layer
protected $attributes = [
'isVisible' => false
];
and you will have the default values when returning a newly created object.

passing an ID of a newly created row within controller

If I have inserted a new row as follows :
$post = new Post();
$post->save();
Is there a straight way to call the post_id just created above and insert it in a new row in another table (instead of changing many things to pass it from a view) ?
$post = new Post();
$post->save();
$talk = new Talk();
$talk->post_id = // I need to put here the post_id just created. Both inserts
//are in the same controller/method
You can use the created post object, since after saved, the post has an unique id:
$post = new Post();
$post->save();
$talk = new Talk();
$talk->post_id = $post->id;
Hope it helps.
If the $post->id is not there yet you can try this
$post = new Post();
$post->save();
$post = $post->fresh();
$talk = new Talk();
$talk->post_id = $post->id;
Either you can do this also. Use Post::latest()->get()->take(1)->pluck('id'); to get the latest added.
Like example below:
$post = new Post();
$post->save();
$talk = new Talk();
$talk->post_id = Post::latest()->get()->take(1)->pluck('id');
->latest()

Append $id to post slug on create in Laravel

I'm creating a blog post from a form using Laravel, and passing the title and body through to the create method in the PostsController.
The slug has to be unique, so although the following works, it fails when I use a duplicate title.
I intended on appending the $post->id to the slug, so this-is-the-post-title would become this-is-the-post-title-12
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use Session;
use Carbon\Carbon;
class PostController extends Controller
{
public function store(Request $request) {
$this->validate($request, [
'title' => 'required|max:255',
'body' => 'required'
]);
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->slug = str_slug($request->input('title'), '-');
$post->save();
Session::flash('success', 'The blog post was successfully saved!');
return redirect()->route('posts.show', $post->id);
}
My initial thought was to concatenate $post->id to the end of the slug, but it doesn't work.
I'm assuming that this is because the id isn't assigned until the save()?
Is there a way to get the id that is going to be used?
I thought of just returning the number of rows in the db, and adding one, but that would fail if two people posted at the same time.
(I'm fairly new to Laravel and taught myself PHP, so this may be glaringly obvious/simple, but any help is appreciated.)
Save first then update later:
$post = \DB::transaction(function() use($request) {
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->slug = uniqid(); //to avoid unique column conflict, it will be overwritten
$post->save();
$post->slug = str_slug($request->input('title').' '.$post->id, '-');
$post->save();
return $post;
});

Laravel:: reuse article id into new table

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();.

Categories