Yii2. Can't get models image path from another table - php

In Product model I have:
public function getImage()
{
return $this->hasMany(Image::className(), ['product_id' => 'id']);
}
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image->path;
}
In view file I have ListView with _item file:
<img src="<?=$model->getMainImage()?>"></img>
Controller:
$dataProvider = new ActiveDataProvider([
'query' => Product::find()->with(['image']),
]);
Error is:
Trying to get property 'path' of non-object.

The code you have submitted may cause this error if the image was not found.
You should include a null check.
public function getMainImage()
{
$image = Image::findOne(['product_id' => $this->id, 'is_main' => 1]);
return $image ? $image->path : false;
}
You may also want to look at implementing this with an AR relation via hasOne, which would be more concise. It is documented here:
https://www.yiiframework.com/doc/api/2.0/yii-db-baseactiverecord#hasOne()-detail

Have you write full code:
return is_null($image) ? false : $image->path;
if not working, check your condition!

Related

Call to a member function all() on array laravel excel

i'm using laravel maatwebsite excel,
i tried passing variable and do some action and return as array to export,
So i get the Error when i tried to pass array to the main controller for excel export(download)
my main controller
public function excel_export(Request $request){
return Excel::download(new UsersExport($request->exp_vlas), 'users.xlsx');
}
here iam passing variable to the collection
my export controller
public function collection(){
$instruments = implode(",",$this->id);
$instruments = explode(",",$instruments);
//$i=0;
foreach ($instruments as $instrument) {
$instr_list = DB::table('instruments')->select('*')->where('id',$instrument)->get()->toArray();
$arr_instrulist[] = $instr_list;
$instrument_var[] = $instrument;
$instr_list = "";
//$i++;
}
$arr_instrulist_excel[] = array('Instrument Name', 'Serial', 'Qa id', 'Unit', 'Range');
foreach($arr_instrulist as $arr_instrulists){
//$arr_instrulists = array($arr_instrulists);
$arr_instrulist_excel[] = array(
'Instrument Name' => $arr_instrulists[0]->instrument_name,
'Serial' => $arr_instrulists[0]->serial,
'Qa id' => $arr_instrulists[0]->qa_identification_no,
'Unit' => $arr_instrulists[0]->unit,
'Range' => $arr_instrulists[0]->range
);
}
return $arr_instrulist_excel;
}
when tried to return this($arr_instrulist_excel) i get an error
please give me some solution for this.
Error i'm facing
You are telling export script to get your data from Collection but you are giving an array. You should return collection instead.
You can simply wrap your array in collection like that:
return collect($arr_instrulist_excel);

Laravel return UploadedFile object instead of image path

In my update method in the controller when i try to dump the requested data
all attributes comes fine but the image printed as object not the imagePath that is saved in the database
Update method
public function update(Request $request, SlideShow $slideshow)
{
$slideshow->update($request->validate([
'title_en' => 'required',
'title_ar' => 'required',
'link' => 'nullable|url',
'image' => 'image'
]));
dd($slideshow);
$slideshow->uploadImage();
session()->flash('success', __('dashboard.slideshow.edit_success'));
return redirect()->route('admin.slideshow.index');
}
SlideShow model
class SlideShow extends Model
{
protected $fillable = ['title_en', 'title_ar', 'link', 'image'];
public function uploadImage($imageName = 'image')
{
if(request()->has($imageName)){
\Storage::delete($this->image);
$uploadedImage = request()->$imageName->store('slideshow/');
\Image::make('storage/'.$uploadedImage)->resize(870, null, function ($constraint) {
$constraint->aspectRatio();
})->save();
$this->update(['image' => $uploadedImage]);
}
}
public static function search($request)
{
return static::where(lang('title'), 'like', '%' . $request->search . '%')->paginate(10);
}
}
This is normal behavior. When the request is made, Laravel converts the files in the request to the UploadedFile class. Since you're accessing the validated data from the request, this is what is returned. You're directly filling these values as attributes, and the UploadedFile doesn't automatically convert to a path, so this should probably not be included in the first update.
Anyway, in your code you're actually including in your question has the dd() method before you call the uploadImage method, and this method saves the path and does not try to safe the entire UploadedFile class. So if you dump it after it probably has the correct value there, can you verify this?
I'd do it like this:
public function update(Request $request, SlideShow $slideshow)
{
// validate first
$data = $request->validate([
'title_en' => 'required',
'title_ar' => 'required',
'link' => 'nullable|url',
'image' => 'image'
]);
// only pull the data that we can update right now
$slideshow->update($request->only(['title_en', 'title_ar','link']));
// handle and store image if needed
$slideshow->uploadImage();
session()->flash('success', __('dashboard.slideshow.edit_success'));
return redirect()->route('admin.slideshow.index');
}
and then the method on the model:
public function uploadImage($imageName = 'image')
{
if(request()->has($imageName)){
\Storage::delete($this->image);
$uploadedImage = request()->$imageName->store('slideshow/');
\Image::make('storage/'.$uploadedImage)->resize(870, null, function ($constraint) {
$constraint->aspectRatio();
})->save();
$this->update(['image' => $uploadedImage->path()]);
}
}

Category isn't getting related video blogs?

I am trying to get category related video blogs by below code but i get nothing in var_dump? I want to get category related videos:
$category = VideoBlogCategoryModel::findFirst(1); // This returns category successfully and there are many video blogs having this category linked
var_dump($category->getVideoBlogs());exit;
VideoBlogModel.php
public function initialize(){
// Run base initialize code
parent::initialize();
// Configure Relation with VideoBlogCategoryModel
$this->belongsTo('category_id', VideoBlogCategoryModel::class, 'id', array(
'alias' => 'videoCategory',
'foreignKey' => true
));
}
public function getVideoCategory(){
return $this->videoCategory;
}
public function setVideoCategory($videoCategory){
$this->videoCategory = $videoCategory;
}
VideoBlogCategoryModel.php
public function initialize(){
// Run base initialize code
parent::initialize();
// Configure relation with VideoBlogModel
$this->hasMany('id', VideoBlogModel::class, 'category_id', array(
'alias' => 'videoBlogs',
'foreignKey' => true,
'cxAction' => static::ACTION_CASCADE_DELETE
));
}
public function getVideoBlogs(){
return $this->videoBlogs;
}
public function setVideoBlogs($videoBlogs){
$this->videoBlogs = $videoBlogs;
}
Let me know if anything else is required, I will share it.
In VideoBlogCategoryModel.php change
public function getVideoBlogs() {
return $this->videoBlogs;
}
to
public function getVideoBlogs() {
return $this->getRelated('videoBlogs');
}
Then try accessing it like:
$category = VideoBlogCategoryModel::findFirst(1);
$videos = $category->getVideoBlogs();
foreach( $videos as $video ) {
// access data here
var_dump($video->anyProperty()); // e.g $video->getId()
}
can you try it
$category = VideoBlogCategoryModel::findFirst(1);
$videos = $category->getVideoBlogs();
var_dump($videos->count());
var_dump($videos->toArray());
exit;
I think use var_dump for a Phalcon Collection Object is not a good idea, you can convert it to Array and Var_dump
Hope it can help you
Or try:
$categories = VideoBlogCategoryModel::findById($id);

Problem with the function update() using Repository pattern to write REST API

I have a problem that all the create-read-delete using Repository Pattern is good but the update function is error. I still have the data but the information is not updated.
This is my code in EventController
public function update(EventRequest $request, $id)
{
$events = $this->repository->update($request->all());
return $this->sendResponse($events->toArray(), 'Successfully updated the Event!!');
}
This is i use DI for inject from the Repository, this is EventRepository.php
public function update($id, array $array) {
$events = $this->model->findOrFail($id);
$events->update($array);
return $events;
}
when i use dd($array) and the result returns [] without anything. Can anyone help me. Did i write anything wrong in this. Or i write the wrong Request
public function rules()
{
// $id = $this->events ? ',' . $this->events->id : '';
return $rules = [
'event_title' => 'required|max:255',
'event_type_id' => 'required|integer|between:1,3',
'from_date' => 'required|date_format:Y-m-d H:i:s',
'to_date' => 'date_format:Y-m-d H:i:s|nullable',
'is_recurring' => 'boolean|required',
'remarks' => 'nullable',
];
}
This method takes two arguments:
public function update($id, array $array) {
However, that's not how you are calling it:
$this->repository->update($request->all());
I take it $request->all() gives you an array, so pass the ID first.
$this->repository->update($id, $request->all());

Modify data before pagination in CakePhp

I'm trying to create an Api using cakephp.
I generate a json on server and it works fine , but I tired to use pagination and I got a problem.
in the first case I take the image's path and I encode it to base64 and I generate json => works
in the second case I defined the pagination by the limits and the max and I kept the same code but as a result the image field is still the path from the database and it's not encoded
this my code in my controller :
class PilotsController extends AppController {
public $paginate = [
'page' => 1,
'limit' => 5,
'maxLimit' => 5
];
public function initialize() {
parent::initialize();
$this->loadComponent('Paginator');
$this->Auth->allow(['add','edit','delete','view','count']);
}
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $this->paginate($pilot));
$this->set('_serialize', ['pilot']);
}
}
If I remove the pagination from the code it works fine . Any idea how to fix it ??
I'd suggest to use a result formatter instead, ie Query::formatResults().
So you'll have something like this :
public function view($id) {
$pilot = $this->Pilots->find()
->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']]);
->formatResults(function($results) {
return $results->map(function($row) {
$image1 = file_get_contents(WWW_ROOT.$row['image_pilot']);
$row['image_pilot'] = base64_encode($image1);
return $row;
});
});
}
You can simply first paginate the data and then get the array values and after that modify that data as you want. Check this
public function view($id) {
$pilot = $this->Pilots->find()->where(['Pilots.account_id' => $id], [
'contain' => ['Accounts', 'Pilotlogs']
]);
$pilot = $this->paginate($pilot);
$pilot = $pilot->toArray();
foreach ($pilot as $obj) {
if ($obj->image_pilot!= NULL) {
$image1 = file_get_contents(WWW_ROOT.$obj->image_pilot);
$obj->image_pilot = base64_encode($image1);
}
}
$this->set('pilot', $pilot);
$this->set('_serialize', ['pilot']);
}

Categories