Laravel Add/Append Base URL to Database Result - php

In my laravel app database, the resource are saved as link like this
/storages/photos/bla-bla.png
what is the best way, so I can append my app url to the result,
www.baseurl.example/storages/photos/bla-bla.png
it's because the backend and front end has difference base url
Thanks

IT can be achieved in two ways
While storing the images/files
$request->photo
->storeAs(
'photos',
config('app.url'). $request->file('photo')->getClientOriginalName()
);
While accessing (via an accessor)
class Some extends Model
{
public function getPhotoAttribute($value)
{
return config('app.url'). $value;
}
public function setPhotoAttribute($value)
{
$this->attributes['photo'] = str_replace(config('app.url'), '', $value);
}
}
You need to set the correct value for APP_URL in the .env file

Related

Yii2 - Render view located in subfolder

I'm working with Yii2 and I wonder which is the right way to render from a controller a file located within a subfolder in views directory. For example, I have the following situation:
views
-campus (carpeta)
--actividad (subcarpeta)
---2020.php (vista)
So far, I've tried this options but without success:
return $this->render('/actividad/2020',[]);
return $this->render('/actividad/2020',[],$this->context);
return $this->render('2020',[],$this->context);
return $this->render('#app/views/campus/actividad/2020',[]);
return $this->render('//actividad/2020',[]);
My controller CampusController:
<?php
namespace frontend\controllers;
class CampusController extends \yii\web\Controller
{
public function action2020()
{
return $this->render('actividad/2020');
//return $this->render('/campus/actividad/2020');
//return $this->render('//campus/actividad/2020');
//return $this->render('#app/views/campus/actividad/2020');
}
}
If you are on CampusController, want to render 2020.php, and have the folder structure that you show in your question:
views
-campus (carpeta)
--actividad (subcarpeta)
---2020.php (vista)
All the following ways would work:
return $this->render('actividad/2020');
return $this->render('/campus/actividad/2020');
return $this->render('//campus/actividad/2020');
return $this->render('#app/views/campus/actividad/2020');
If you are not passing any parameters to the view, you can pass an empty array, but you can also remove the second parameter.
You do need to return the result of $this->render(...), in your question it looks like you are calling return after, that would return an empty response instead of the result of rendering the view file.

How to read config values in PHP controller?

I am using symfony 4.2 framework in which there is PHP controller with multiple actions. I have set below values in packages\config.yaml.
myDir: '/abc'
I have below controller with 2 actions as defined below.
//this works
public function uploadTestAction(Request $r_request)
{
$myDir = $r_request->request->get("myDir");
}
//this doesn't work
public function loadTestAction(Request $r_request)
{
$myDir = $r_request->request->get("myDir");
//$myDir = $r_request->query->get("myDir"); //this is also not working
}
Issue here is I am able to get the value in uploadTestAction but value is coming as null in uploadTestAction. I have tried using query as well but still not getting the correct value. Both request types are GET. What I am missing here or how can trace it ?
you should define it as parameter:
https://symfony.com/doc/current/service_container/parameters.html
final class XyController extends SymfonyController {
public function registerAction() {
$dir = $this->container->getParameter('dir');
}
}

Cache wrapper for DB model

I have been trying to find the best way to create a cache wrapper for all models. So all the DB lookup are done through the model, but the model decides if the results should be stored in cache.
For example, when I search for a user by email, I want to do something like User->getByEmail('test#exmaple.com');
My User model would contain a function that looks something like
public static function getByEmail($email) {
$cache = self::cacheFetch($email);
if($cache) {
return $cache;
}
// DB lookup to get data
self::cacheStore($email, $data);
return $data;
}
cacheFetch and cacheStore are defined as traits. The App name and table name are prepended to the cache key to avoid key clash.
How do I do the database lookup within the Model?
Is there a better way to achieve what I am trying to do here?
You actually only need one function, cacheFetch. This function would check if the queried data is in cache and if not, load the data from the database.
This is a small example of how the function could work:
protected function cacheFetch($email)
{
$slug = 'db_' . self::getTable() . '_' . $email;
// Try fetching data from cache
if (cache()->has($slug)) {
return cache($slug);
}
// Fetch data from database and put in cache
$data = self::where('email', $email)->get();
cache()->put($slug, $data, 60);
return $data;
}

Add a custom attribute when retrieving a model

Is possible to attach a custom attribute when retrieving a model in laravel?.
The problem is that I need to return some data that is not in the database along the info from the database. I've been doing it manually but I guess that there might be a way to do it in the model.
Example: I have an application table. Each application contains a folder with documents with the same application id. I need to attach the amount of files the folder that correspond to each application.
This is what I do:
$application = Application::get();
$application = $application->map(function($a){
$a->files = $this->getFiles($a->id); // This gets the amount of files
return $a;
})
Is there some way to do it in the model in a way that $application->files is already contained in $application when doing Application::get()
class User extends Model
{
public function getFooBarAttribute()
{
return "foobar";
}
}
And access to that attribute like:
$user->foo_bar;
or like,
$user->fooBar;
More detailed documentation;
https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor
in the Application model
public function getFilesAttribute()
{
return 'lala'; // return whatever you need;
}
now application model has an attribute named files.
$application->files // returns lala.
example code.
$applications = Application::get();
$application_files = applications->map->files;
official documentation https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

Laravel load custom config

I'm trying to integrate custom code into my Laravel project, here's the current folder structure :
You can see my controllers and models - views are in a module subfolder and I already made the controller and views run properly, but now I want to load a config file under module/Csol/Fight/Config, named development.php (for example) - here's my current attempt :
In my controller :
public function __construct()
{
$namespacePath = substr(__NAMESPACE__, 0, strrpos(__NAMESPACE__, "\\"));
View::addNamespace($namespacePath, app_path()."/module/".str_replace("\\", "/", $namespacePath).'/views');
Config::addNamespace($namespacePath, app_path()."/module/".str_replace("\\", "/", $namespacePath).'/Config');
var_dump(get_class(Config::getFacadeRoot()));
}
public function showWelcome()
{
// View::addLocation(app_path().'/module/Csol/Fight/views');
echo "<pre>";
var_dump($this);
echo "</pre>";
var_dump(Csol\Fight\Config::getItems());
die();
return View::Make("Csol\Fight::a");
}
development.php:
return array(
"dbs"=>array(
"host"=>"sss",
"db_name"=>"ccc",
)
);
I can't get the result of my own config file, any help please ?
Problem fixed...
takes me a little more time...
I should use this var_dump(Config::get('Csol\Fight::development.xxx'));
instead of var_dump(Csol\Fight\Config::getItems());
have fun...

Categories