I'm retrieving a users profile picture with:
Auth::user()->photo->thumbnail
In the user model I can see this:
public function getPhotoAttribute()
{
$file = $this->getMedia('photo')->last();
if ($file) {
$file->url = $file->getUrl();
$file->thumbnail = $file->getUrl('thumb');
$file->preview = $file->getUrl('preview');
}
return $file;
}
However, when the user didn't upload a picture, I want to use a default picture. I have honestly no idea how. I've tried changing the function to this:
$file = $this->getMedia('photo')->last();
if (!$file) {
$file = asset("public/default.jpg");
}
$file->url = $file->getUrl();
$file->thumbnail = $file->getUrl('thumb');
$file->preview = $file->getUrl('preview');
return $file;
But that gives "Call to a member function getUrl() on string".
Anyone could help me on the way!
Thanks
Laravel asset() function returns the URL as string. Can see here: https://laravel.com/docs/8.x/helpers#method-asset
You can do something like this...
Just return your default image paths with the help of asset() function if the file doesn't exists.
public function getPhotoAttribute()
{
$file = $this->getMedia('photo')->last();
if ($file) {
$file->url = $file->getUrl();
$file->thumbnail = $file->getUrl('thumb');
$file->preview = $file->getUrl('preview');
} else {
$file->url = asset("public/default.jpg");
$file->thumbnail = asset("public/default-thumb.jpg");
$file->preview = asset("public/default-preview.jpg");
}
return $file;
}
Related
here my code and i want to save image url in database i am using laravel my question is how i save image url in database
public function save(Request $req)
{
if(request()->hasFile('photo')){
$path = base_path() . '/public/user-uploads/employee-docs/';
$repath = '/public/user-uploads/employee-docs/'.request('project');
if (!file_exists($path))
{
mkdir($path);
}
$path = $path.'/'.request('project');
if (!file_exists($path))
{
mkdir($path);
}
$name = Carbon::now()->format('Y-m-d-H-i-s_u');
$file1 = request()->file('photo');
if($file1->isValid()) {
$file1->move($path, $name.'.'.$file1->getClientOriginalExtension());
$file1_url = $repath.'/'.$name.'.'.$file1->getClientOriginalExtension();
$photo = new attendance;
$photo ->user_id=$req->user_id;
$photo ->image_url=$req->image_url;
return ['status'=>1, 'data'=>$file1_url];
} else{
return ['status'=>0, 'data'=>'Invalid image'];
}
} else{
return ['status'=>0, 'data'=>'There is no image'];
}
}
Looks like you have not saved the object $photo
$photo = new attendance;
$photo->user_id=$req->user_id;
$photo->image_url=$req->image_url;
$photo->save() // add this line
Can anybody help as I am trying to use the codeigniter's upload library from the helpers folder but I keep getting the same error that I am not selecting an image to upload? Has any body tried this before?
class FileUpload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'file_uploading'));
$this->load->library('form_validation', 'upload');
}
public function index() {
$data = array('title' => 'File Upload');
$this->load->view('fileupload', $data);
}
public function doUpload() {
$submit = $this->input->post('submit');
if ( ! isset($submit)) {
echo "Form not submitted correctly";
} else { // Call the helper
if (isset($_FILES['image']['name'])) {
$result = doUpload($_FILES['image']);
if ($result) {
var_dump($result);
} else {
var_dump($result);
}
}
}
}
}
The Helper Function
<?php
function doUpload($param) {
$CI = &get_instance();
$CI->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|png|jpg|jpeg|png';
$config['file_name'] = date('YmdHms' . '_' . rand(1, 999999));
$CI->upload->initialize($config);
if ($CI->upload->do_upload($param['name'])) {
$uploaded = $CI->upload->data();
return $uploaded;
} else {
$uploaded = array('error' => $CI->upload->display_errors());
return $uploaded;
}
}
There are some minor mistakes in your code, please fix it as below,
$result = doUpload($_FILES['image']);
here you should pass the form field name, as per your code image is the name of file input.
so your code should be like
$result = doUpload('image');
then, inside the function doUpload you should update the code
from
$CI->upload->do_upload($param['name'])
to
$CI->upload->do_upload($param)
because Name of the form field should be pass to the do_upload function to make successful file upload.
NOTE
Make sure you added the enctype="multipart/form-data" in the form
element
I have this code source that i'm trying to use in one of my projects, it worked with laravel 5.2. This the function in the assetController:
namespace App\Http\Controllers;
use App\Setting;
use File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AssetController extends Controller
{
/**
* List all image from image directory
*/
public function getAsset()
{
//Get Admin Images
$adminImages = array();
//get image file array
$images_dir = Setting::where('name', 'images_dir')->first();
$folderContentAdmin = File::files($images_dir->value);
//check the allowed file extension and make the allowed file array
$allowedExt = Setting::where('name', 'images_allowedExtensions')->first();
$temp = explode('|', $allowedExt->value);
foreach ($folderContentAdmin as $key => $item)
{
if( ! is_array($item))
{
//check the file extension
$ext = pathinfo($item, PATHINFO_EXTENSION);
//prep allowed extensions array
if (in_array($ext, $temp))
{
array_push($adminImages, $item);
}
}
}
//Get User Images
$userImages = array();
$userID = Auth::user()->id;
$images_uploadDir = Setting::where('name', 'images_uploadDir')->first();
if (is_dir( $images_uploadDir->value . "/" .$userID ))
{
$folderContentUser = File::files($images_uploadDir->value . "/" .$userID );
if ($folderContentUser)
{
foreach ($folderContentUser as $key => $item)
{
if ( ! is_array($item))
{
//check the file extension
$ext = pathinfo($item, PATHINFO_EXTENSION);
//prep allowed extensions array
//$temp = explode("|", $this->config->item('images_allowedExtensions'));
if (in_array($ext, $temp))
{
array_push($userImages, $item);
}
}
}
}
}
//var_dump($folderContent);
//var_dump($adminImages);
return view('assets/images', compact('adminImages', 'userImages'));
}
The problem is in the line 21 :
//get image file array
$images_dir = Setting::where('name', 'images_dir')->first();
$folderContentAdmin = File::files($images_dir->value);
From my research I find out that the reason is because the setting table is empty which it is true.
Please tell me if there is another cause to that problem if it's not the case I need a solution because I don't have a way to fill that table except doing it from the database itself (phpmyAdmin)
I have modified the _prepareLayout() function in Mage_Catalog_Block_Category_View class to have a customized canonical url. After modifying the URL, the canonical code does not display in the html source code anymore.
Here are my codes:
protected function _prepareLayout() {
Mage_Core_Block_Template::_prepareLayout();
$this->getLayout()->createBlock('catalog/breadcrumbs');
if ($headBlock = $this->getLayout()->getBlock('head')) {
$category = $this->getCurrentCategory();
if ($title = $category->getMetaTitle()) {
$headBlock->setTitle($title);
}
if ($description = $category->getMetaDescription()) {
$headBlock->setDescription($description);
}
if ($keywords = $category->getMetaKeywords()) {
$headBlock->setKeywords($keywords);
}
if ($this->helper('catalog/category')->canUseCanonicalTag()) {
//$headBlock->addLinkRel('canonical', $category->getUrl());
if ($category->getCategoryUrlAlias()) {
$url = Mage::getBaseUrl() . $category->getCategoryUrlAlias();
} else {
$key = $this->helper('my_package/category')->getIsTitleCategoryKey($category);
$url = $category->getUrl();
$url = $this->_removeKeyFromUrl($url, $key);
}
$headBlock->addLinkRel('canonical', $url);
}
/*
want to show rss feed in the url
*/
if ($this->IsRssCatalogEnable() && $this->IsTopCategory()) {
$title = $this->helper('rss')->__('%s RSS Feed', $this->getCurrentCategory()->getName());
$headBlock->addItem('rss', $this->getRssLink(), 'title="' . $title . '"');
}
}
return $this;
}
I have verified that the $url variable always have the customized url value that I want. I'm wondering if there is any validation function that's preventing me to have a customized canonical URL?
Any help will be greatly appreciated. Thanks!
Is there a way to show the changed values after saving within the Joomla save method?
For example, when I edit a "maxuser" field and save it, I´d like to show the old and the new value.
I tried this by comparing "getVar" and "$post", but both values are the same.
function save()
{
...
$maxuser1 = JRequest::getVar('maxuser');
$maxuser2 = $post['maxuser'];
...
if($maxuser1 != $maxuser2) {
$msg = "Not the same ...";
}
...
}
It's better to override JTable, not the Model. Heres sample code:
public function store($updateNulls = false) {
$oldTable = JTable::getInstance(TABLE_NAME, INSTANCE_NAME);
$messages = array();
if ($oldTable->load($this->id)) {
// Now you can compare any values where $oldTable->param is old, and $this->param is new
// For example
if ($oldTable->title != $this->title) {
$messages[] = "Title has changed";
}
}
$result = parent::store($updateNulls);
if ((count($messages) > 0) && ($result === true)){
$message = implode("\n", $messages);
return $message;
} else {
return $result;
}
}
This will return message string if there are any, true if there are no messages and save succeeded and false if saving failed. So all you have to do is check returned value in model and set right redirect message.
In the controller you can use the postSaveHook which gives you access to the validated values.