How to add laravel-medialibrary into Laravel/mongodb app? - laravel

I need to add spatie/laravel-medialibrary 10 into Laravel 9 app with jenssegers/mongodb:^3.9
I modified model app/Models/CMSItem.php decalaration :
<?php
namespace App\Models;
use Carbon;
use Jenssegers\Mongodb\Eloquent\Model;
use Illuminate\Validation\Rule;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class CMSItem extends Model implements HasMedia
{
use InteractsWithMedia;
use HasFactory;
protected $collection = 'cms_items';
public $timestamps = true;
But I got error :
Call to a member function prepare() on null
with code :
foreach ($cMSItems as $nextCMSItem) {
$this->media_image_url = '';
$this->file_name = '';
foreach ($nextCMSItem->getMedia(config('app.media_app_name')) as $mediaImage) { // this line raised the error
$nextCMSItem->media_image_url = $mediaImage->getUrl();
$nextCMSItem->file_name = $mediaImage->file_name;
}
}
Reading docs https://spatie.be/docs/laravel-medialibrary/v10/advanced-usage/using-your-own-model
I try to define custom model in config/media-library.php :
...
// 'media_model' => Spatie\MediaLibrary\MediaCollections\Models\Media::class,
'media_model' => App\Models\CustomMongoMedia::class,
...
and I created file app/Models/CustomMongoMedia.php with content:
<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model;
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;
class CustomMongoMedia extends BaseMedia
{
protected $collection = 'cms_items';
public $timestamps = true;
}
But I got the same error.
If I modify this file:
class CustomMongoMedia extends Model
{
protected $collection = 'cms_items';
public $timestamps = true;
}
But I got error:
Spatie\MediaLibrary\MediaCollections\MediaRepository::__construct():
Argument #1 ($model) must be of type Spatie\MediaLibrary\MediaCollections\Models\Media, App\Models\CustomMongoMedia given, called in
/mnt/_work_sdb8/wwwroot/lar/MngProducts/vendor/spatie/laravel-medialibrary/src/MediaLibraryServiceProvider.php on line 35
In which way can it be salved ?
Thanks!

Related

How to pass variable from Controller to Nova Recource?

I want to pass $defaultFrom from NewsletterController.php:
<?php
namespace App\Http\Controllers;
use App\Mail\NewsletterMail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
class NewsletterController extends Controller
{
public function send()
{
$defaultFrom = 'newsletter#stuttard.de';
DB::table('newsletter_mails')->insert(['from' => $defaultFrom]);
$emails = DB::select('select * from newsletters order by id desc');
foreach ($emails as $email) {
Mail::to($email)->send(new NewsletterMail());
}
}
}
to NewsletterMail.php:
<?php
namespace App\Nova;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
class NewsletterMail extends Resource
{
public function fields(Request $request)
{
return [
ID::make(__('ID'), 'id')->sortable(),
Text::make('From', 'from')->default($defaultFrom)->placeholder($defaultFrom),
];
}
}
I've tried to put public $defaultFrom; above the fields() function or call new NewsletterMail($defaultFrom) but this seems to be wrong syntax. Sorry, I'm a bit new to Laravel.
I assume that you have Newsletter model. Move $defaultFrom to model as public const DEFAULT_FROM = 'newsletter#stuttard.de';. After doing this, you can call it's value in both places using Newsletter::DEFAULT_FROM.

How to merge two collection of model and make it as one paginate then send it to the view in Laravel

I want to send two collection model to view and make it as one paginate......but im still confused when i want to paginate as the two collection models
Here's my model RefHoliday.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class RefHoliday extends Model
{
//
public $timestamps = false;
public $incrementing = false;
protected $table = 'refHoliday';
}
second model -- HDHolidayCalendar.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class HDHolidayCalendar extends Model
{
//
public $timestamps = false;
public $incrementing = false;
protected $table = 'Holiday_Calendar';
}
holiday controller
public function index()
{
$refHol = RefHoliday::all();
$HolCal = HDHolidayCalendar::all();
// $paginationRecord = ??
return view('administration.holiday.HolidayMasterList', compact('??'));
}
I try to explore to solve this things but seems not clearly explain...
To merge two collection.
$refHol = RefHoliday::all();
$holCal = HDHolidayCalendar::all();
$data = $refHol->merge($holCal);

Laravel: Class not found if it is called from a Trait

After creating several Apps with Laravel and using softDelete properties I realized that methods like destroy(), restore() and kill() are exactly the same among several controllers. Therefore I am trying to put themn in a trait and use it from diferent Controllers.
My code is as follows:
ProfilesController.php
<?php
namespace App\Http\Controllers;
use App\Profile;
class ProfilesController extends Controller
{
public function destroy(Profile $profile)
{
Profile::del($profile, 'profiles');
return redirect()->route('profiles.index');
}
public function trashed()
{
Profile::trash('Profile');
}
}
Profile.php (model)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Profile extends Model
{
protected $fillable = ['user_id', 'role_id', 'title', 'subtitle', 'slug', 'birthday', 'about'];
use SoftDeletes, Helpers, commonMethods;
public function getRouteKeyName()
{
return 'slug';
}
// ... more code here
}
trait file: commonMethods.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use App\Profile;
use Session;
trait commonMethods
{
public static function del($element, $page_name)
{
$element->delete();
Session::flash('success', $element . ' successfully deleted!');
}
public static function trash($model)
{
$total = $model::onlyTrashed()->get();
$total_tr = count($total);
$all_tr = $model::all();
return view('partials.templates.trashed', compact('total', 'total_tr', 'all_tr'));
}
// ...more code here
}
The problem:
I try to visit the view "Trashed" that will list all elements "softdeleted" but not "killed", the method.
I pass the $model variable with the method trash($model)
I get the following error:
Class App/Profile does not found. Try to call App/Profile
I have debugged and the $model variable contains exactly what I need, the string 'Profile' which is what I need to build the Query:
$total = Profile::onlyTrashed()->get();
This query works while in the ProfilesController, but does not work while in a trait, since the model class is not found.
Any idea how could I make it work?
I am using Laravel 6.
If you need to use a class as a string you will want to use its full name. 'App\Profile' instead of 'Profile'.
$model = 'Profile';
new $model; // will use `\Profile`
$model = 'App\Profile';
new $model; // will use '\App\Profile';
In your controller( ProfilesController ) write :
use App\Profile;
In your model write :
use App\commonMethods;

Laravel Join Query return Invalid Object Name

I have two Models (Color and ColorFamily Table).I would like to join two table.When I join Second Table (ColorFamily),its shows an error message "Invalid Object Name ColorFamily".If I use to Join First Table then its shows an error message "Invalid Object Name Color".
Note:-
If I use Individual Query (Select Query) without join ,then the records is showing,that means both the tables are available...
I have check with google but can not find the solution.....
Color Models:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Color extends Model
{
protected $primaryKey = 'ColorId';
protected $table = 'Common_Ref_Color';
public $timestamps = false;
}
ColorFamily Models:-
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ColorFamily extends Model
{
protected $primaryKey = 'ColorFamilyId';
protected $table = 'Common_Ref_ColorFamily';
public $timestamps = false;
}
Controller:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Http\Requests;
use App\Models\ColorFamily;
use App\Models\Color;
class ColorController extends Controller
{
public function Index()
{
$Data = Color::select ('ColorId','ColorName','ColorCode','ColorShortCode')
->join('ColorFamily','ColorFamilyId','=','Color.ColorFamilyId')
->get();
return $Data;
}
}
Can you try the following code:
class ColorController extends Controller {
public function Index()
{
$Data = DB::table('Color')
->select ('ColorId','ColorName','ColorCode','ColorShortCode')
->join('ColorFamily','ColorFamily.ColorFamilyId','=','Color.ColorFamilyId')
->get();
return $Data;
}
}
I think that you need to add joined table name inside join
('ColorFamily.ColorFamilyId','=','Color.ColorFamilyId')

Custom pivot model class does not exist in controller

I got a pivot table which holds extra data. So i created a custom pivot model like shown in the docs for Laravel 5.6.
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PersonaTreeleave extends Pivot
{
public $timestamps = false;
protected $table = 'persona_treeleave';
protected $fillable = [
'FK', 'RoleTitle', 'Merkmale'
];
public function treeleave_id(){
return $this->hasOne('App\Treeleave');
}
public function persona_id(){
return $this->hasOne('App\Persona');
}
}
In a controller file i want to attach a user to an already existing "treeleave".
App\Treeleave::where('cid',$P['OE'])
->where( 'tree', $Baum->id)->first()
->Persons()->attach($DBUser, [
'FK' => $P['FK'],
'RoleTitle' => $P['RoleTitle'],
'Merkmale' => json_encode($P['Merkmale'])
]
);
I keep getting an error like "Class 'App\PersonaTreeleave' not found".
I dont get why that happens. It doesn't help if i add "Use App\PersonaTreeleave" in the controller file.
If i do this
dump(class_exists('App\Treeleave'));
dump(class_exists('App\PersonaTreeleave'));
it generates this output:
true
false
Anybody got a hint?
The classes for "treeleave" and "persona"
namespace App;
use Illuminate\Database\Eloquent\Model;
class Treeleave extends Model
{
protected $table = 'treeleaves';
public $timestamps = false;
protected $fillable = ['parent','lft','rgt','ebene','oe_titel','tree','meta'];
public function Baum(){
return $this->belongsTo('App\Tree');
}
public function Persons(){
return $this->belongsToMany('App\Persona')
->withPivot('FK', 'RoleTitle', 'Merkmale')
->using('App\PersonaTreeleave')
;
}
}
namespace App;
use Illuminate\Database\Eloquent\Model;
class Persona extends Model
{
public $timestamps = false;
protected $attributes = [
'titel' => ''
];
protected $fillable = [
'nachname', 'vorname', 'titel', 'projekt', 'email', 'geschlecht', 'cid'
];
public function logins(){
// erwartet Relations-Tabelle "login_project" (alphabetische Reihenfolge der beteiligten Tabellen, Namen im Singular)
return $this->belongsToMany('App\Login');
}
public function OE(){
return $this->belongsToMany('App\Treeleave')
->withPivot('FK', 'RoleTitle', 'Merkmale')
->using('App\PersonaTreeleave')
;
}
public function setTitelAttribute($value)
{
$this->attributes['titel'] = (string)$value;
}
}
Try running:
composer dump-autoload
To update your autoload file with the new class info.

Resources