cannot using attach() method in laravel - php

I have the following relations set up:
public function notes()
{
return $this->belongsToMany(Note::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
and pivot table like this:
Schema::create('note_tag', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('note_id')->unsigned()->index();
$table->foreign('note_id')->references('id')->on('tags')->onDelete('cascade')->onUpdate('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('notes')->onDelete('cascade')->onUpdate('cascade');
});
now, i used Attach() method:
$note->tags()->attach($tagsIds);
but that doesn't work and I get this error:
[Symfony\Component\Debug\Exception\FatalErrorException]
Cannot instantiate interface phpDocumentor\Reflection\DocBlock\Tag

Looks like you've imported the wrong class that corresponds to Tag::class.
It should probably be something like this:
use App\Tag;
instead of:
use phpDocumentor\Reflection\DocBlock\Tag;

Related

Call to undefined method attach()

Hi am trying to use a many to many relationship but I cannot see what im doing wrong. This:
$meeting = new Meeting();
$meeting->attach($user);
causes: BadMethodCallException: Call to undefined method App\Models\Meeting::attach()
User model
public function meetings(): BelongsToMany
{
return $this->belongsToMany(Meeting::class);
}
Meeting Model
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class);
}
Migration
Schema::create('meeting_user', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('meeting_id');
$table->unsignedBigInteger('user_id');
$table->timestamps();
});
Attach is called in the relationship, not in the model. You should use it like this:
$meeting->users()->attach($user);
Take a look at https://laravel.com/docs/7.x/eloquent-relationships#updating-many-to-many-relationships.
You have to use like this
$meeting->users()->attach($request->user); // user may have input field name

App\Tasks::first()->projects; in artisan tinker returns null, no matter what :(

The following code in tinker returns a null value while it should return the project to which the first task is linked.
App\Task::first()->projects;
Already tried renaming the method names, column names in migrations, tried exiting tinker and logging back in
Project Migration
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('title');
$table->string('description');
$table->timestamps();
});
}
Task Migration
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('project_id');
$table->string('description');
$table->boolean('completed')->default(false);
$table->timestamps();
});
}
Project.php
use App\Task;
class Project extends Model
{
protected $fillable = ['title','description'];
public function tasks(){
return $this->hasMany(Task::class);
}
}
Task.php
use App\Project;
class Task extends Model
{
protected $fillable = [
'completed'
];
public function projects(){
return $this->belongsTo(Project::class);
}
}
If anyone could just review this piece of code and let me know where I have made any conventional\idiotic mistakes (since Im new to route model binding) it would be of great help!
A task belongs to a project, so rename projects to project as it is singular. If you keep projects then provide the column name as second parameter:
public function projects(){
return $this->belongsTo(Project::class, 'project_id');
}
// I suggest this
public function project(){
return $this->belongsTo(Project::class);
}
Your column types are different, for the id of the project you use Big Integer and for the reference you use Integer, so this:
$table->unsignedInteger('project_id');
should be this:
$table->unsignedBigInteger('project_id');
// also good to make the relationship on the Database level:
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');

Undefined property: Illuminate\Database\Eloquent\Relations\MorphMany::$title

Sorry for bad English at first )
I'm new to laravel5 and trying to use polymorphic relations
here is the code
class Post extends Model
{
public function seo()
{
return $this->MorphMany('App\Seo' , 'seoable');
}
}
class Seo extends Model
{
public function seoble()
{
return $this->morphTo();
}
}
and in the view I try to retrieve post seo data like this
$post->seo()->title;
here is my DB
Schema::create('seos', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('keywords');
$table->text('description');
$table->string('og_type');
$table->string('og_title');
$table->text('og_description');
$table->integer('seoable_id');
$table->string('seoable_type');
$table->timestamps();
});
but I got the error
Undefined property:
Illuminate\Database\Eloquent\Relations\MorphMany::$title (View: /Applications/MAMP/htdocs/lblog/resources/views/posts/form.blade.php)
Try this:
$post->seo->first()->title; or $post->seo()->get()->first()->title;
the reason why it doesn't work because the the seo() function until now is just a query, you need to execute that query like above

laravel eloquent for hasMany relation does not work

I have these relations in my database
Schema::create('my_users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('fullName');
$table->string('userName');
$table->string('password');
$table->string('photo');
$table->string('email');
});
and
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('photo');
$table->text('caption');
$table->integer('like');
$table->integer('my_user_id');
});
my models :
class myUser extends Model
{
public function post()
{
return $this->hasMany('App\post');
}
}
class post extends Model
{
public function user()
{
return $this->belongsTo('App\myUser');
}
}
now I'm trying to get a user's data using the following code :
$post = post::find(1);
$user = $post->user;
but it doesn't work and $user is NULL.
I'm sure that in posts table there is a record with id 1.
the weird part is this that I get no error when I change the method's name like this :
$post = post::find(1);
$user = $post->somethingBullshit;
I'm using laravel 5.3.
help please.
Confirm that you are naming your class files starting with upper case letters, and modify your class declarations accordingly, such as:
class MyUser extends Model
{
public function post()
{
return $this->hasMany('App\Post');
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\MyUser');
}
}
You can then select the user when you obtain the post by utilizing eloquent's with() method, and obtain your $user variable from your $post variable, OR just use the user property of post as follows:
$post = Post::with('user')->find(1);
$user = $post->user;

Laravel 5: Redirect "blog/{id}" to "blog/{slug}" - Trying to get property of non-object error

I'm trying to redirect users that go to blog/{id} to blog/{slug} with the slug being the slug of the id they entered.
What I am doing is not working. I dd{$article->slug} and get the correct string, yet when I try to redirect I get "Trying to get property of non-object" error.
I'm using route/model binding. This is my RouteServiceProvider:
$router->bind('blog', function($slug)
{
if ($slug) {
if(is_numeric($slug)) {
$article = Article::findOrFail($slug);
return redirect('blog/' . $article->slug);
}
return Article::with('images')->where('slug', $slug)->first();
}
});
This is my show method in controller:
public function show(Article $article)
{
return view('blog.show', compact('article'));
}
Any ideas would be greatly appreciated!
articles migration file:
class CreateArticlesTable extends Migration
{
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('slug');
$table->text('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
public function down()
{
Schema::drop('articles');
}
}
Your controller is expecting an instance of Article. So, if you're returning a RedirectResponse from your closure, it won't work.
At the moment, I can only think of 2 ways of achieving what you want with route-model binding.
The first method is simpler. Just don't type-hint the Article. Instead, check if it's a RedirectResponse. If so, return it. If not, return the view. Something like this:
public function show($article)
{
if ($article instanceof \Illuminate\Http\RedirectResponse)
{
return $article;
}
return view('blog.show', compact('article'));
}
You could also check if it's an instance of an Article just to be absolutely certain since you're no longer type-hinting.
The second method is overly complex in my opinion for a simple check. You would have to throw a custom exception, catch it from within app/Exceptions/Handler.php, and then redirect from there.

Categories