Laravel Method sync does not exist - laravel

Post Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function tags(){
return $this->belongsToMany('App\Model\User\Tag','post__tags', 'post_id', 'tag_id');
}
public function categories() {
return $this->belongsToMany('App\Model\User\Category','category__posts','post_id', 'category_id');
}
}
Category Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function posts(){
return $this->belongsToMany('App\Model\User\Category','category__posts', 'post_id', 'category_id');
}
}
Tag Model
<?php
namespace App\Model\User;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
public function posts() {
return $this->belongsToMany('App\Model\User\Post','post__tags','post_id','tag_id');
}
}
PostController.php
public funcion store()
{
// do validation here
try{
$post = new Post;
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->slug = $request->slug;
$post->body = $request->body;
$post->status = 1;
$post->save(); // This works correct
$post->tags->sync($request->tags); // Not working
$post->categories->sync($request->categories); // Not working
}
catch(\Exception $e){
return redirect(route('post.index'))->with('message', 'Error Adding Post into system!'.$e->getMessage()); // getting Message "Method sync does not exist. "
}
}

Sync is a method on the builder instance, you're using it on the collection.
// change your code like this
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);

You need to use the following:
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
Don't forget the () in tags and categories
$post->categories without () is a Collection instance.
$post->categories() is a belongsToMany instance

Related

laravel call to undefined method app\models\User:id()

I have been trying to create a point system, so after much effort i am getting this error which i could not figure out how to solve it because this is my first time working so deep
I have checked code but couldn't pinpoint the error
call to undefined app\models\User:id()
point model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Point extends Model
{
use HasFactory;
const TABLE = 'points';
protected $table = self::TABLE;
protected $fillable = [
'id', 'amount', 'message', 'current_points'
];
public function pointable(): MorphTo
{
return $this->morphTo();
}
public function getCurrentPoints(Model $pointable)
{
$currentPoints = Point::where('pointable_id', $pointable->id())
->where('pointable_type', $pointable->getMorphClass())
->orderBy('created_at', 'desc')
->pluck('current_points')->first();
if($currentPoints){
$currentPoints = 0;
}
return $currentPoints;
}
public function addAwards(Model $pointable, $amount, $message)
{
$award = new Static();
$award->amount = $amount;
$award->current_points = $this->getCurrentPoints($pointable) + $amount;
$award->message = $message
$pointable->awards()->save($award);
return $award;
}
}
pointable model
<?php
namespace App\Models;
interface pointable
{
public function awards();
public function countAwards();
public function addPoints($amount, $message);
}
hasPoints Traits
<?php
namespace App\Traits;
use App\Models\Point;
trait HasPoints
{
public function awards($amount = null)
{
return $this->morphMany(Point::class, 'pointable')
->orderBy('created_at', 'desc')
->take($amount);
}
public function countAwards()
{
return $this->awards()->count();
}
public function currentPoints()
{
return (new Point())->getCurrentPoints($this);
}
public function addPoints($amount, $message)
{
return (new Point())->addAwards($this, $amount, $message);
}
}
AwardPointLItener
?php
namespace App\Listeners;
use App\Events\ReplyWasCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class AwardPointForNewReply
{
public function handle(ReplyWasCreated $event)
{
$amount = config('points.rewards.new_reply');
$message = 'User Created A New Reply';
$author = $event->reply->user;
$author->addPoints($amount, $message);
}
}
ReplyEvent
<?php
namespace App\Events;
use App\Models\Reply as Replyers;
use Illuminate\Queue\SerializesModels;
class ReplyWasCreated
{
use SerializesModels;
public $reply;
public function __construct(Replyers $reply)
{
$this->reply = $reply;
}
}
livewire reply componet
use Livewire\Component;
use App\Models\Reply as Replys;
class Reply extends Component
{
public $thread;
public $username;
public $reply_text;
public $replyCommentId = NULL;
protected $rules = [
'reply_text' => 'required'
];
public function mount(Thread $thread)
{
$this->thread = $thread;
}
public function render()
{
$replys = Replys::whereNull('parent_id')
->with('replies')
->with('user')
->where('thread_id', $this->thread->id)->paginate()->withQueryString();
return view('livewire.thread.reply',[
'replys' => $replys,
]);
}
public function save_reply()
{
$this->validate();
$replyevent = Replys::create([
'thread_id' => $this->thread->id,
'user_id' => auth()->user()->id,
'reply_text' => $this->reply_text,
'parent_id' => $this->replyCommentId
]);
event(new ReplyWasCreated($replyevent));
// $this->username = '';
$this->reply_text = '';
$this->replyCommentId = NULL;
}
public function deleteReply($id)
{
$reply = Replys::FindOrFail($id);
$reply->delete();
}
public function replys($replyId)
{
$this->replyCommentId = $replyId;
}
}
To get the id of a model, you simply access its id property. There is no id() method.
$currentPoints = Point::where('pointable_id', $pointable->id)

Laravel generates error while sending lists of posts to users

RegistrationController.php
use App\User;
use App\Post;
use App\Notifications\LatestPosts;
use App\Notifications\WelcomeEmail:
public function store()
{
auth()->login($user);
$allUsers = User::latest()->get();
$posts = Post::latest()->get();
$user->notify(new WelcomeEmail($user));
$allUsers->notify(new LatestPosts($posts));
return redirect(‘/dashboard’);
}
WelcomeEmail.php
use App\User;
class WelcomeEmail extends Notification
{
use Queueable:
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function toMail($notifiable)
{
$user = $this->user;
return (new MailMessage)
->subject(‘Thanks for registering’)
->markdown(‘emails.newusers.welcome’, compact(‘user’));
}
}
LatestPosts.php
use App\Post;
class LatestPosts extends Notification
{
use Queueable;
public $posts;
public function __construct(Post $posts)
{
$this->posts = $posts;
}
public function toMail($notifiable)
{
$posts = $this->posts;
return (new MailMessage)
->subject(‘Latest posts for you’)
->markdown(‘emails.posts.latestposts’, compact(‘posts’));
}
}
New users register successfully, welcome email is sent successfully but it gives me this error for sending latest posts to users.
Argument 1 passed to App\Notifications\LatestPosts::__construct() must be an instance of App\Post, instance of Illuminate\Database\Eloquent\Collection given
Basically, I want to send a list of posts to all users (I know it’s not efficient to send it while new users register but just want to see how it will work out even if I send it while new users register) Someone please help me out in this. What do I do? Thanks in advance.
In registration controller
use App\User;
use App\Post;
use App\Notifications\LatestPosts;
use App\Notifications\WelcomeEmail:
public function store()
{
auth()->login($user);
$allUsers = User::latest()->get();
$posts = Post::latest()->get();
$user->notify(new WelcomeEmail($user));
foreach($allUsers as $u){
$u->notify(new LatestPosts($posts));
}
return redirect(‘/dashboard’);
}
LatestPost
use App\Post;
use Illuminate\Database\Eloquent\Collection;
class LatestPosts extends Notification
{
use Queueable;
public $posts;
public function __construct(Collection $posts)
{
$this->posts = $posts;
}
public function toMail($notifiable)
{
$posts = $this->posts;
return (new MailMessage)
->subject(‘Latest posts for you’)
->markdown(‘emails.posts.latestposts’, compact(‘posts’));
}
}
You should change the signature of your constructor:
use App\Post;
use Illuminate\Database\Eloquent\Collection;
class LatestPosts extends Notification
{
use Queueable;
public $posts;
public function __construct(Collection $posts) // use `Collection`, not `Post`
{
$this->posts = $posts;
}
public function toMail($notifiable)
{
$posts = $this->posts;
return (new MailMessage)
->subject('Latest posts for you')
->markdown('emails.posts.latestposts', compact('posts'));
}
}

Unable to show data in Laravel

I am adding a feature in chatter package and now am unable to show data on my view
this is the code of controller ChatterreplyController.php
<?php
namespace DevDojo\Chatter\Controllers;
use Illuminate\Http\Request;
use DevDojo\Chatter\Models\Chatterreply;
use Auth;
use Carbon\Carbon;
use DevDojo\Chatter\Events\ChatterAfterNewDiscussion;
use DevDojo\Chatter\Events\ChatterBeforeNewDiscussion;
use DevDojo\Chatter\Models\Models;
use Illuminate\Routing\Controller as Controller;
use Event;
use Validator;
class ChatterreplyController extends Controller
{
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
return back()->with('chatter_alert','Add Comment Successfully');
}
public function show(Chatterreply $chatterreply ,$id)
{
$chatterreplies = Chatterreply::where('chatter_post_id',$id)->get();
return view('chatter::discussion', compact('chatterreplies'));
echo "<pre>"; print_r('$chatterreplies'); die;
}
}
this is the view page discussion.blade.php
#foreach($chatterreplies as $chatterreply)
{{$chatterreply->reply}}
#endforeach
try this:
public function store(Request $request)
{
$chatterreply = new Chatterreply;
$chatterreply->reply = $request->body;
$chatterreply->chatter_post_id = $request->chatter_post_id;
$chatterreply->chatter_discussion_id = $request->chatter_discussion_id;
$chatterreply->save();
return redirect('/discussion')->with('chatter_alert','Add Comment Successfully');
}

Controller For One To Many Relationships

I'm using Laravel 5.2.
I have 3 tables (writters, publishers and categories) all of the is One to Many Relationships with table named books.
I'm not really sure what the problem is, but everytime i call the the column from 2 of them (nama_penerbit from publishers table and nama_kategori from categories table)from my view blade, it throws me an error Trying to get property of non-object
Here is my models
Book.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $fillable = [
'judul',
'label',
'isbn',
'tanggal_terbit',
'status',
'id_penulis',
'id_penerbit',
'id_kategori',
];
// Book with Writter
public function writter()
{
return $this->belongsTo('App\Writter', 'id_penulis');
}
// Book with Publisher
public function publisher()
{
return $this->belongsTo('App\Writter', 'id_penerbit');
}
// Book with Category
public function category()
{
return $this->belongsTo('App\Writter', 'id_kategori');
}
}
Publisher.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Publisher extends Model
{
protected $fillable = [
'nama_penerbit',
];
// Relation Book with Publisher
public function book() {
return $this->hasMany('App\Book', 'id_penerbit');
}
}
Writter.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Writter extends Model
{
protected $fillable = [
'nama_penulis',
];
// Relation Book with Writter
public function book() {
return $this->hasMany('App\Book', 'id_penulis');
}
}
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = [
'nama_kategori',
];
// Relation Book with Category
public function book() {
return $this->hasMany('App\Book', 'id_kategori');
}
}
my-view.blade.php
<span>{{ $book->writter->nama_penulis }}</span> // works like a charm
<span>{{ $book->publisher->nama_penerbit }}</span> // throw me an error
<span>{{ $book->category->nama_kategori }}</span> // throw me an error
My question is why nama_penerbit and nama_kategori throw a error while the other one works well
Any sugestion?
You're using Writter model for all three relationships, so fix these relationships by setting correct models:
// Book with Publisher
public function publisher()
{
return $this->belongsTo('App\Publisher', 'id_penerbit');
}
// Book with Category
public function category()
{
return $this->belongsTo('App\Category', 'id_kategori');
}

FatalErrorException Laravel 5.3 Post Controllers

hi i have task title social network application using post and timeline
i have some problem
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function postCreatePost(Request $request)
{
$post = new Post();
$post->body = $request['body'];
$request->user()->posts()->save($post);
return redirect()->('home');
}
}
this is my Post modle please check this code
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user (){
return $this->belongsTo('App\User');
}
}
Try to change
$post = new Post();
To
$post = new Post;
1) Change:
$post->body = $request['body'];
to:
$post->body = $request->get('body');
2) This line: $request->user()->posts()->save($post); also seems all wrong.
In your User model you need to tell eloquent that a user has many posts
public function posts()
{
return $this->hasMany('App\Post');
}
Then that line in your controller for a user with id = 1; $user = User::find(1) becomes:
$user->posts()->save($post)
3)return redirect()->('home'); has to be return redirect()->route('home');
4) Lastly, take some time to read the laravel documentation

Resources