Create new Post with default Category belongsToMany - laravel

I have a Post/Category manyToMany relations and would like to be able to attach a default category named "Uncategorised" to each new post that is created. How can I do that? A BelongsToMany method only works on the Details page, not on Create page.
BelongsToMany::make(__('Categories'), 'categories', Category::class),

You can also set default value to your database field so that you can omit passing category and will be taken default to Uncategorised like if you are using MySQL you can do it this way by creating migration
$table->text('category')->default(0);

Because the BelongsToMany not show on mode create in Post Nova model. So we have to make our custom Select, by add this code to your fields:
public function fields(Request $request)
{
if($request->editMode=="create"){
$categories = \App\Category::get(['id','name']);
$options = [];
foreach($categories as $value){
$options[$value->id] = $value->name;
}
return [
ID::make()->sortable(),
Text::make('Title'),
Text::make('Summary'),
Textarea::make('Content'),
Select::make('Categories', 'category_id')
->options($options)
->displayUsingLabels()
->withMeta(['value' => 1]) // 1 = id of Uncategorised in categories table
];
}
return [
ID::make()->sortable(),
Text::make('Title'),
Text::make('Summary'),
Textarea::make('Content'),
BelongsToMany::make('Categories','categories')->display('name'),
];
}
Don’t forget relationship function in both, Post and Category model:
class Post extends Model
{
public function categories(){
return $this->belongsToMany(Category::class, 'category_post', 'post_id', 'category_id');
}
}
And:
class Category extends Model
{
public function posts(){
return $this->belongsToMany(Post::class,'category_post', 'category_id', 'post_id');
}
}
Then, custom the function process the data on mode Create of Post resource page, it’s at nova\src\Http\Controllers\ResourceStoreController.php, change function handle to this:
public function handle(CreateResourceRequest $request)
{
$resource = $request->resource();
$resource::authorizeToCreate($request);
$resource::validateForCreation($request);
$model = DB::transaction(function () use ($request, $resource) {
[$model, $callbacks] = $resource::fill(
$request, $resource::newModel()
);
if ($request->viaRelationship()) {
$request->findParentModelOrFail()
->{$request->viaRelationship}()
->save($model);
} else {
$model->save();
// your code to save to pivot category_post here
if(isset($request->category_id)&&($resource=='App\Nova\Post')){
$category_id = $request->category_id;
$post_id = $model->id;
\App\Post::find($post_id)->categories()->attach($category_id);
}
}
ActionEvent::forResourceCreate($request->user(), $model)->save();
collect($callbacks)->each->__invoke();
return $model;
});
return response()->json([
'id' => $model->getKey(),
'resource' => $model->attributesToArray(),
'redirect' => $resource::redirectAfterCreate($request, $request->newResourceWith($model)),
], 201);
}
}
All runs well on my computer. A fun question with me! Hope best to you, and ask me if you need!

What I ended up doing was saving the data on Post Model in boot().
public static function boot()
{
parent::boot();
static::created(function (Post $post) {
$post->categories()->attach([1]);
});
}

Related

How to call a function in one controller to the other controller in laravel

I want to call a function in another controller. when i call this gives me an error.
Call to undefined method Illuminate\Database\Query\Builder::defaultBuckets()
I dont know why it gives me this error. I don't know i am calling this function rightly in another controller. Here is my code. Please Help.
Here is my function i created in my BucketController:
public function defaultBuckets()
{
$buckets = Bucket::where('bucket_type', 'default')->get();
}
And here is my Profile controller function Where i call this function:
public function show(User $user)
{
$authUser = JWTAuth::parseToken()->toUser();
if (! $user->isBlocking($authUser) && ! $user->isBlockedBy($authUser)) {
if($authUser->id == $user->id){
$profile = $user->where('id', $user->id)->defaultBuckets()->with([
'posts', 'likes', 'followers', 'following'])->first();
} else{
$profile = $user->where('id', $user->id)->with([
'posts' => function ($query) {
$query->where('post_type', 'public');
},
'buckets' => function ($query) {
$query->where('bucket_type', 'public');
},
'likes' => function ($query) {
$query->where('post_type', 'public');
},
'followers', 'following'])->first();
}
return response()->json(['profile'=> $profile], 200);
}
return response()->json(['message'=> 'Your are not able to open profile of this user'], 200);
}
I Think there is mistake. You said you have this function in your BucketController
public function defaultBuckets()
{
$buckets = Bucket::where('bucket_type', 'default')->get();
}
and then you are firing the function from user model in your ProfileController
$profile = $user->where('id', $user->id)->defaultBuckets()->with([
'posts', 'likes', 'followers', 'following'])->first();
That is the reason it says that there is no function named "defaultBuckets".
You have to put this function in your User model and everything will work fine.
Also don't forget to return the buckets as well like this:
To return all buckets
public function defaultBuckets()
{
$buckets = Bucket::where('bucket_type', 'default')->get();
return $buckets; // all buckets
}
To return a user's buckets only
public function defaultBuckets()
{
return $this->hasMany(Bucket::class)->where('bucket_type', 'default');
}
Make sure to accept the relationship from user in bucket model like this:
public function user(){
return $this->hasOne(User::class, 'bucket_id' , 'user_id');
}
You can replace column names (bucket_id,user_id) according to your database.
Let me know if this fixes your problem

Populating a pivot table with Laravel/Eloquent

I have 8 tables: products, pests, actives, crops, active_product, pest_product, crop_product, and active_pest
I've built a form that loads information about a selected (agrichemical) product - in that form, the user selects the pests, actives, and crops associated with that product. When submitted, my existing code is saving the expected information in the products table and, through a set of "belongsToMany" relationships, the active_product, pest_product, and crop_product pivot tables are also correctly updated.
My problem is that I do not know how to use the actives and pests information (i.e. their respective id values) to add to/update the active_pest table.
I'd appreciate some direction.
The methods in my models are as follow:
product
public function Actives()
{
return $this->hasMany('App\Models\Active','active_product', 'product_id', 'active_id');
}
public function pest()
{
return $this->belongsToMany('App\Models\Pest','pest_product', 'product_id', 'pest_id');
}
public function active()
{
return $this->belongsToMany('App\Models\Active','active_product', 'product_id', 'active_id');
}
active
public function product()
{
return $this->belongsToMany('App\Models\Product', 'active_product', 'active_id', 'product_id');
}
public function pest()
{
return $this->belongsToMany('App\Models\Pest', 'active_pest', 'active_id', 'pest_id');
}
pest
public function active()
{
return $this->belongsToMany('App\Models\Active', 'active_pest', 'pest_id', 'active_id');
}
public function product()
{
return $this->belongsToMany('App\Models\Product','pest_product', 'pest_id', 'product_id');
}
public function crop()
{
return $this->belongsToMany('App\Models\Crop','crop_pest', 'pest_id', 'crop_id');
}
I am using BackPack for Laravel - my Product controller contains this function for updating:
public function update(UpdateRequest $request)
{
$redirect_location = parent::updateCrud($request);
return $redirect_location;
}
updateCrud is
public function updateCrud(UpdateRequest $request = null)
{
$this->crud->hasAccessOrFail('update');
$this->crud->setOperation('update');
// fallback to global request instance
if (is_null($request)) {
$request = \Request::instance();
}
// update the row in the db
$item = $this->crud->update($request->get($this->crud->model->getKeyName()),
$request->except('save_action', '_token', '_method', 'current_tab', 'http_referrer'));
$this->data['entry'] = $this->crud->entry = $item;
// show a success message
\Alert::success(trans('backpack::crud.update_success'))->flash();
// save the redirect choice for next time
$this->setSaveAction();
return $this->performSaveAction($item->getKey());
}
Thanks, Tom
you can use laravel's attach method like this:
$actives = App\Active::create([
'someColumn' => 'test',
'anotherColumn' => 'test',
]);
$pests = App\Pest::create([
'someColumn' => 'test',
'anotherColumn' => 'test',
]);
$actives->pest()->attach($pests);
^^^-relation name in model

Laravel Nova + Spatie Media library

Trying to use Laravel Nova with Spatie Media Library. I created upload field like this:
Image::make('Logo')
->store(function (Request $request, $model) {
$model->addMediaFromRequest('logo')->toMediaCollection('manufacturers');
}),
Seams ok, but Nova still trying to save file name to "logo" column in manufacturers table.
Original excample to customize this field was:
File::make('Attachment')
->store(function (Request $request, $model) {
return [
'attachment' => $request->attachment->store('/', 's3'),
'attachment_name' => $request->attachment->getClientOriginalName(),
'attachment_size' => $request->attachment->getSize(),
];
})
I found a work around by setting an empty mutator on the model. In your case it would be:
class Manufacturer extends Model implements HasMedia
{
use HasMediaTrait;
public function setLogoAttribute() {}
//...
}
Here's an example of my entire implementation. Note that currently with Nova 1.0.6, the preview() method is not working, it's returning the thumbnail() url.
App/GalleryItem
class GalleryItem extends Model implements HasMedia
{
use HasMediaTrait;
public function setImageAttribute() {}
public function registerMediaConversions(Media $media = null)
{
$this->addMediaConversion('thumbnail')
->fit(Manipulations::FIT_CROP, 64, 64);
$this->addMediaConversion('preview')
->fit(Manipulations::FIT_CROP, 636, 424);
$this->addMediaConversion('large')
->fit(Manipulations::FIT_CONTAIN, 1920, 1080)
->withResponsiveImages();
}
public function registerMediaCollections()
{
$this->addMediaCollection('images')->singleFile();
}
}
App/Nova/GalleryItem
class GalleryItem extends Resource
{
public static $model = 'App\GalleryItem';
public static $with = ['media'];
public function fields(Request $request)
{
return [
Image::make('Image')
->store(function (Request $request, $model) {
$model->addMediaFromRequest('image')->toMediaCollection('images');
})
->preview(function () {
return $this->getFirstMediaUrl('images', 'preview');
})
->thumbnail(function () {
return $this->getFirstMediaUrl('images', 'thumbnail');
})
->deletable(false);
];
}
}
As with Nova 3 (and Laravel 8) you need to return true from the fillUsing or store method:
File::make('Attachment')
->store(function (Request $request, $model) {
$model->addMediaFromRequest('logo')->toMediaCollection('manufacturers');
return true;
// This will tell nova that you have taken care of it yourself.
})
As soon as you return anything but true nova will assume, that it needs to save something to the database. This leads to an error if the field does not exist in db (as to expect with spatie-medialibrary) or it will overwrite your precious data if the field exists but serves another purpose.
Nova allows you to return true from the callback to indicate that the processing is complete and that it shouldn't set any attributes itself.
This is the code that runs the callback:
protected function fillAttribute(NovaRequest $request, $requestAttribute, $model, $attribute)
{
//...
$result = call_user_func($this->storageCallback, $request, $model);
if ($result === true) {
return;
}
if (! is_array($result)) {
return $model->{$attribute} = $result;
}
foreach ($result as $key => $value) {
$model->{$key} = $value;
}
}
So either true or any empty array will achieve the same thing, but personally feels clearer to do the former.
Image::make('Logo')
->store(function (Request $request, $model) {
$model->addMediaFromRequest('logo')->toMediaCollection('manufacturers');
return [];
}),
Maybe returning an empty array prevent nova from saving the name.

How can I add, delete and get a favorite from product with polymorphic relationship, in Laravel 5.6?

My product model like this :
<?php
...
class Product extends Model
{
...
protected $fillable = ['name','photo','description',...];
public function favorites(){
return $this->morphMany(Favorite::class, 'favoritable');
}
}
My favorite model like this :
<?php
...
class Favorite extends Model
{
...
protected $fillable = ['user_id', 'favoritable_id', 'favoritable_type'];
public function favoritable()
{
return $this->morphTo();
}
}
My eloquent query laravel to add, delete and get like this :
public function addWishlist($product_id)
{
$result = Favorite::create([
'user_id' => auth()->user()->id,
'favoritable_id' => $product_id,
'favoritable_type' => 'App\Models\Product',
'created_at' => Carbon::now()
]);
return $result;
}
public function deleteWishlist($product_id)
{
$result = Favorite::where('user_id', auth()->user()->id)
->where('favoritable_id', $product_id)
->delete();
return $result;
}
public function getWishlist($product_id)
{
$result = Favorite::where('user_id', auth()->user()->id)
->where('favoritable_id', $product_id)
->get();
return $result;
}
From the code above, I'm using parameter product_id to add, delete and get data favorite
What I want to ask here is : Whether the above is the correct way to add, delete and get data using polymorphic relationship?
Or is there a better way to do that?

Failed to insert multiple tags on Laravel

I want to insert a Post record with multiple tags so here's my code in Post#store:
$post = Post::create(array(
'title' => $request->title,
'body' => $request->body,
'user_id' => Auth::id(),
));
if($post && $request->tags)
{
$tagNames = explode(',', $request->tags);
$tagIds = [];
foreach($tagNames as $tagName)
{
$tag = Tag::firstOrCreate(['name'=>$tagName]);
if($tag)
{
$tagIds[] = $tag->id;
}
}
$post->tags()->attach($tagIds);
}
but it give me an errors "Call to a member function attach() on null". when i'm checked in mysql the tags is already in there but i can't find any entry on my post_tag tables. here's my post model:
class Post extends Model
{
protected $fillable = ['user_id','title','slug','body','tags','category_id','featured'];
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
$this->hasMany('App\Tag');
}
}
You need to return the call the hasMany in your Post model.
public function tags()
{
return $this->hasMany('App\Tag');
}
Update
You should use belongsToMany not hasMany.

Resources