I'm using laravel voyager with laravel 9 and I have an issue with the scope, the code is as follows:
public function scopeUser($query)
{ $products = DB::table('products')->select('id')->where('stakeholders_id', auth()->user()->id);
// dd($products);
$table = DB::table('product_variations')->whereIn('product_id',$products);
// dd($table);
return $table;
}
when I dd the $table variable I get the correct values needed when I add ->get() at the end but when I remove both I get all the rows in the database when I need only the authenticated user's product variations, any ideas??
tray this
public function scopeUser($query)
{
$products = Product::where('stakeholders_id', auth()->id());
if (count($products) > 0) {
if (count($products) > 1) {
$pluckIds = $products->pluck('id')->toArray();
$table = DB::table('product_variations')->whereIn('product_id', $pluckIds)->get();
return $table;
}else{
$pluckIds = $products->first()->id;
$table = DB::table('product_variations')->where('product_id', $pluckIds)->get();
return $table;
}
}else{
return false;
}
}
Related
I am having issue while keeping the same slug if we don't change title while updating, slug take the value of title. I have made a function to create slug. But when i update the same function automatically changes slug because it already exists in DB.
public function createSlug($title, $id = 0)
{
$slug = str_slug($title);
$allSlugs = $this->getRelatedSlugs($slug, $id);
if (! $allSlugs->contains('slug', $slug)){
return $slug;
}
$i = 1;
$is_contain = true;
do {
$newSlug = $slug . '-' . $i;
if (!$allSlugs->contains('slug', $newSlug)) {
$is_contain = false;
return $newSlug;
}
$i++;
} while ($is_contain);
}
// slug function
protected function getRelatedSlugs($slug, $id = 0)
{
return Post::select('slug')
->where('slug', 'like', $slug.'%')
->where('id', '<>', $id)
->get();
}
First of all, you don't need to create a function for that. Just validation will be enough.
use Illuminate\Support\Str;
$validator = $request->validate([
'slug' => ['required''unique:post'],
]);
if ($validator->fails()) {
$generate_extension = Str::random(3);;
}
$newSlug = str_slug($request->title).'-'.$generate_extension;
Then assign the slug.
$post->slug = $newSlug;
In order to keep the same slug you can check if title is changed;
if($post->slug != str_slug($request->title)){
$post->slug = str_slug($request->title);
}
or
if($post->title != $request->title){
$post->slug = str_slug($request->title);
}
When i store a new record, Laravel returns the new record. Everything works fine.
When i update a record, Laravel returns the old record. I like to return the updated record.
Controller
public function store(StoreProjectRequest $request)
{
$data = $this->repo->create( $request->all());
return response()->json(new ProjectResource($data));
}
public function update(UpdateProjectRequest $request, Project $project)
{
$data = $this->repo->update($project, $request->all());
return response()->json(new ProjectResource($data));
}
Repository
public function create( $data)
{
$this->model->name = $data['name'];
$this->model->description = $data['description'];
$this->model->sales_order_id = $data['sales_order_id'] ? $data['sales_order_id'] : NULL;
$this->model->project_leader_id = $data['project_leader_id'];
$this->model->project_type_id = $data['project_type_id'];
$this->model->project_status_id = $data['project_status_id'];
$this->model->creator_id = Auth()->id();
$this->model->save();
return $this->model;
}
public function update($model, $data)
{
$model->name = $data['name'];
$model->description = $data['description'];
$model->sales_order_id = $data['sales_order_id'];
$model->project_leader_id = $data['project_leader_id'];
$model->project_type_id = $data['project_type_id'];
$model->project_status_id = $data['project_status_id'];
$model->save();
return $model;
}
When i add $data = Project::find($project->id)i receive the updated model.
But is this the only way?
The reason the $data is returning as the old data is because it still stores the data from when the variable was created. When you call $data->fresh() it will go fetch the new data and return it. Does that make sense?
I'm use laravel 5.6 on this project. Categories value not recorded 'categorizables' pivot table. I check with f12 or bug but I do not get any errors. all of them ok but not recorded pivot table. Where I have
been mistake.
My Blog project sql structure is below
--blogs
id
title
description
...
-- categorizables
category_id
categorizable_id
categorizable_type
Below code belong to Category.php Model
class Category extends Model
{
protected $primaryKey='category_id';
public function blogs(){
return $this->morphedByMany('App\Blog', 'categorizable', 'categorizables', 'category_id');
}
}
Above code belong to Blog.php
public function category($categories)
{
$categories = Blog::buildCatArray($categories);
foreach ($categories as $catName) {
$this->addOneCat($catName);
$this->load('categories');
}
return $this;
}
public function buildCatArray($categories): array
{
if (is_array($categories)) {
$array = $categories;
} elseif ($categories instanceof BaseCollection) {
$array = $this->buildCatArray($categories->all());
} elseif (is_string($categories)) {
$array = preg_split(
'#[' . preg_quote(',;', '#') . ']#',
$categories,
null,
PREG_SPLIT_NO_EMPTY
);
} else {
throw new \ErrorException(
__CLASS__ . '::' . __METHOD__ . ' expects parameter 1 to be string, array or Collection; ' .
gettype($categories) . ' given'
);
}
return array_filter(
array_map('trim', $array)
);
}
protected function addOneCat(string $catName)
{
$cat = Self::findOrCreate($catName);
$catKey = $cat->getKey();
if (!$this->cats->contains($catKey)) {
$this->categories()->attach($catKey);
}
}
public function find(string $catName)
{
return $this->Category::$catName->first();
}
public function findOrCreate(string $catName): Category
{
$cat = $this->find($catName);
if (!$cat) {
$cat = $this->Category::create(['name' => $catName]);
}
return $cat;
}
This my Blog Controller file store class
BlogController.php
public function store(Request $request)
{
$data = new Blog;
$data->title = $request->title;
$data->content = $request->content;
$tags = explode(',',$request->tag);
$categories = explode(',',$request->category);
$data->save();
$data->tag($tags);
$data->category($categories);
}
Best wishes
I have an entity and each entity has an address.
I have 2 tables with relationship such as:
Entity:
protected $table = 'entities';
public $timestamps = true;
use Searchable;
public function address()
{
return $this->hasOne('App\Address', 'entity_id');
}
Address:
protected $table = 'address';
public $timestamps = true;
public function entity()
{
return $this->belongsTo('App\Entity', 'id');
}
and my controller:
public function update(EntityRequestUpdate $request)
{
$id = $request->input('entity_id');
$entity = Entity::with('address')
->find($id);
$entity->name = $request->input('name');
$entity->type = $request->input('type');
$entity->email = $request->input('email');
$entity->twitter_entity = $request->input('twitter');
$entity->facebook_entity = $request->input('facebook');
$entity->instagram_entity = $request->input('instagram');
$entity->google_places = $request->input('google');
$entity->address->building_name = $request->input('address1');
$entity->address->street = $request->input('address2');
$entity->address->town = $request->input('town');
$entity->address->city = $request->input('city');
$entity->address->postcode = $request->input('postcode');
$entity->address->telephone = $request->input('telephone');
$entity->address->save($entity);
$entity->save();
$result = $entity->save();
if($result){
$message = 'success';
}else{
$message = 'error';
}
return redirect()->back()->withInput()->with('message', $message);
}
An error message is:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::save() must be of the type array, object given, called in C:\xampp\htdocs\laravel\app\Http\Controllers\EntityController.php on line 146
How can I solve this issue?
I think you just need to use save() method without any parameters. I have try it in php artisan tinker with same structure. And after I get same error, I try to remove the $entity parameter inside save() method:
// After update, you should only use save() not save($entity)
$entity->address->save();
I hope I give correct answer for your problem :-D
I have a problem with database select function, in my custom model. This is the code
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('inflector');
}
public function fetch($parameters = array(), $raw = FALSE)
{
$tablename = $this->getTableName();
$this->select_fields(FALSE == empty($parameters['fields']) ? $parameters['fields'] : FALSE);
unset($parameters['fields']);
if (FALSE == empty($parameters['limit'])) $limit = $parameters['limit'];
if (FALSE == empty($parameters['offset'])) $offset = $parameters['offset']; else $offset = 0;
unset($parameters['limit']);
unset($parameters['offset']);
if (FALSE == empty($limit))
{
$this->db->limit($limit, $offset);
}
$this->parseFilters($parameters);
$query = $this->db->get($tablename);
if ($query->num_rows() > 0)
{
if ($raw)
return $query;
$rows = $query->result();
$objects = array();
foreach ($rows as $row)
$objects[] = $this->hidrate($row);
return $objects;
}
else
{
return array();
}
}
protected function select_fields($fields)
{
if (TRUE == empty($fields))
{
$fields = "`" . $this->getTableName() . "`.*";
}
$this->db->select($fields);
}
public function fetchOne($parameters = array())
{
$parameters['limit'] = 1;
$list = $this->fetch($parameters);
if (FALSE == empty($list))
{
return reset($list);
}
else
{
return null;
}
}
Expecifict in $this->db->select($fields);
Fatal error: Call to a member function select() on a non-object
The model is a custom model and the applicacions model extends of this model. The question is why throws that error the database is correct.
I have a MY_loader create in codeginiter 1.7 and I try update to codeigniter 2
class MY_Loader extends CI_Loader
{
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
if ( substr($model, -4) == '_dao' )
{
return parent::model('dao/' . $model, $name, $db_conn);
}
parent::model( 'dao/' . $model . '_dao', $model, $db_conn);
include_once APPPATH . '/models/' . $model . EXT;
}
}
I don't know how update this model to codeigniter 2 and I believe this Loader generates error with my MY_Model
I'll try troubleshooting why does db return as a non-object.
I'd remove all code and start with a simple select(), if that works, I'll start adding code gradually and see where it breaks.
everything seems to be in order but first you'll need to see if the basic functionality exists.
so
1)remove all code, see if a basic select() works, if it doesn't, troubleshoot further.
2)if it does, keep adding code and see what breaks the select() statement.
3)keep adding code until you spot the issue.