I need to return URL path and name image from database.
This my call method to get data from database:
public function index(){
$rav=Rav::select('id','image','nameravs')->get('image');
return $this->sendResponse($rav->toArray(),'rav show is succesfuly');
}
Output data it look like this:
{
"id": 88,
"image": "1579781806.png",
"nameravs": "asdad"
},
But I want to return image with path URL like this:
"image": http://127.0.0.1:8000/images_ravs/1579781806.png
You can use Eloquent Accessor
add the image url attribute in Rav.php Model like below. then you can access it any place.
public function getImageUrlAttribute($value)
{
return env('APP_URL'). '/images_ravs/' . $this->image;
}
And don't forget to Add Appends property inside the Model
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = ['image_url'];
then you can access it like below.
$rav->image_url
Define An Accessor in your model like this example :
public function getImageAttribute($value)
{
return env('APP_URL') . Storage::url($value);
}
Try this:
public function index(){
$rav = Rav::select('id','image','nameravs')->get('image');
return $this->sendResponse(
[
'id' => $rav->id,
'image' => URL::to('/').'/images_ravs/'.rav->image,
'nameravs' => $rev->nameravs
],'rav show is succesfuly');
}
You can use selectRaw or select with DB::raw and just concat that path as a prepended string infront of your image column in your query:
Rav::select(DB::raw("id, nameravs, CONCAT('/images_ravs/', image) as image"))->get()->toArray();
No need to include the URL (unless for some reason you have some type of CDN in front of it) in which case you can just escape the string and add it if necessary.
I would do something like this: Try to use as many od Laravel's built-in functions as possible. In most cases you don't need to reinvent the wheel.
public function index(){
$ravs = Rav::select('id','image','nameravs')->get();
$results = [];
foreach($ravs as $rav){
$rav->image = env('APP_URL') . '/images_ravs/' . $rav->image;
array_push($results, $rav);
}
return response()->json($results);
}
In the Model you can create getAttribute:
public function getImageAttribute()
{
return $this->attributes['image'] ? URL::to('/uploads/' . $this->attributes['image']) : null;
}
Or you can create custom casts file:
protected $casts = [
'image' => ImageCast::class,
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
Related
I'm trying to test an update to an Eloquent model...
/** #test */
public function updates_to_json_fields_are_logged()
{
$data = json_encode(["json_key" => "old_value"]);
$individual = Individual::factory()->create([
"information" => $data
]);
json_decode($individual->information)->json_key = "new_value";
$individual->save();
echo(var_dump($individual));
$this->assertTrue(false);
}
information is a json column.
When I log $individual after saving it, the value of "information->json_key" is still "old_value". Can anyone tell me why?
To change the $individual object without fancy assign
/** #test */
public function updates_to_json_fields_are_logged()
{
$data = json_encode(["json_key" => "old_value"]);
$individual = Individual::factory()->create([
"information" => $data
]);
$decodedInformation = json_decode($individual->information);
$decodedInformation->json_key = "new_value";
$individual->information = json_encode($decodedInformation);
$individual->save();
echo(var_dump($individual));
$this->assertTrue(false);
}
You don't change original $individual object, but the result of json_decode().
I have two models in laravel project Item and ItemImgs
Item.php
class Item extends Model
{
protected $appends = [
'photo',
];
public function imgs()
{
return $this->hasMany(ItemImage::class);
}
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src;
}
}
it's worked in views
dd(Item::all()); //worked
{{ $cane->photo}}; //worked
but when I try to get json
return response()->json([
'items' => Item::with('imgs')->get(),
]);
// not worked. Got timeout 500
You cannot use dot notation in PHP.
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src; // Dot notation is not allowed
}
but you've to use:
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img->src;
}
if what you're trying to do is to get the items that have imgs() then what you should do is query by relationship existence, as mentioned in the docs
https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence
'items' => Item::has('imgs')->get()
It is not possible to refer to the linked model tables in attributes. It works in views but gives out a memory error when outputting an array through json.
public function getPhotoAttribute(){
$img = ItemImage::where('item', $this->id)-
>first();
}
It works that way, but it's not elegant.
In Yii2 framework is it possible to add a new attribute dynamically to an existing object, which is retrieved from Database?
Example
//Retrieve from $result
$result = Result::findone(1);
//Add dynamic attribute to the object say 'result'
$result->attributes = array('attempt' => 1);
If it is not possible, please suggest an alternate best method to implement it.
Finally I would be converting the result to a json object. In my application, at the behaviour code block, I have used like this:
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
You can add define a public variable inside your model, that will store dynamic attributes as associative array. It'll look something like this:
class Result extends \yii\db\ActiveRecord implements Arrayable
{
public $dynamic;
// Implementation of Arrayable fields() method, for JSON
public function fields()
{
return [
'id' => 'id',
'created_at' => 'created_at',
// other attributes...
'dynamic' => 'dynamic',
];
}
...
..in your action pass some dynamic values to your model, and return everything as JSON:
public function actionJson()
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$model = Result::findOne(1);
$model->dynamic = [
'field1' => 'value1',
'field2' => 2,
'field3' => 3.33,
];
return $model;
}
In result you will get JSON like this:
{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}}
class CreditRule extends Model
{
protected $fillable = array(
'department_id',
'created_by',
'updated_by'
);
public function department()
{
return $this->belongsTo('App\Department');
}
And my controller is
$creditRules = CreditRule::get();
You mean something like
CreditRule::find(1);
This will retrieve the row where id=1 for model CreditRule.
#Eliza, You can use where in your controller while accessing data from model.
Simple structure of where this is :
$creditRules = CreditRule::where('id', 1)->first();
Get model by id:
$element = Model::find(id)
Get all rows of model by matching a field:
$element = Model::where('field','=',$value)->get()
Or to get the first one only:
$element = Model::where('field','=',$value)->first()
I am attempting to filter a piece of input data but would like to do so without an anonymous function. The first example below works but the second example returns the error listed. I don't want the couple dozen lines of validation code sitting directly inside my rules so I would like a way to break it out (as in the second example I am trying to implement.
Example 1 (works but is not what I want to do)
public function rules()
{
return [
['roles', 'filter', 'filter' => function ($value) {
// Do some stuff to remove invalid roles
return $value;
}];
}
Example 2 (does not work but is what I would like to do)
public function rules()
{
return [
['roles', 'filter', 'filter' => 'checkRoles'],
];
}
public function checkRoles($value)
{
// Do some stuff to remove invalid roles
return $value;
}
Error returned for Example 2 above
call_user_func() expects parameter 1 to be a valid callback,
function 'validateRoles' not found or invalid function name
Why does the second example above not work? Or rather, more importantly, what do I need to change to get the second example to work?
You should use a valid callback, e.g. :
public function rules()
{
return [
['roles', 'filter', 'filter' => [$this, 'checkRoles']],
];
}
Read more : http://php.net/manual/language.types.callable.php
You may have to use a structure like this:
'filter' => array( $this, 'checkRoles' )