I'm trying to write a clean code in laravel By using trait For uploading img And I Have A Problem In The code
This Is The Controller
I Used this Also So It Can Work in The Controller
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Traits\Uploadimg;
use Illuminate\Http\Request;
use App\Http\Requests\Userstore;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
This Is The Controller
public function store(Userstore $request)
{
$user = new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
$user->uimg = $request->uimg;
$this ->uimg($request -> uimg , 'uploads/users');
// $file_extension = $request -> uimg -> getclientoriginalExtension();
// $file_name = time ().'.'.$file_extension;
// $path = 'uploads/users';
// $request -> uimg -> move($path,$file_name);
$user->save();
return redirect()->back()->with(['success' => 'User has been added']);
}
This is the Trait File
<?php
namespace App\Traits;
Trait Uploading
{
function uimg(){
if($request->hasFile('uimg')){
$file = $request->file('uimg');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/users/' , $filename);
$user->uimg = $filename;
}
else{
return $request;
$user->uimg = '';
}
// $file_extension = $request -> uimg -> getclientoriginalExtension();
// $filename = time ().'.'.$file_extension;
// $path = 'uploads/users';
// $request -> uimg -> move($path,$filename);
// return $filename;
}
}
I Want to Add the img to The Database Who Can i Do This
Related
Controller
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Signin extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->helper('cias');
$this->load->model('home_model');
$this->load->model('signin_model');
}
public function index(){
$this->is_signed_in();
}
function is_signed_in()
{
$is_signed_in = $this->session->userdata('is_signed_in');
if(!isset($is_signed_in) || $is_signed_in != TRUE)
{
// header
$data['logo'] = $this->home_model->get_logo_by_id();
// footer
$data['contact']=$this->home_model->get_contact();
$this->load->view('front/signin');
}
else
{
redirect('front/dashboard');
}
}
public function signinme()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|max_length[128]|trim');
$this->form_validation->set_rules('password', 'Password', 'required|max_length[32]');
if($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
$email = strtolower($this->security->xss_clean($this->input->post('email')));
$password = $this->input->post('password');
$result = $this->signin_model->sign_in_me($email, $password);
if(!empty($result))
{
$session_array = array('user_id'=>$result->user_id,
'name'=>$result->name,
'email'=>$result->email,
'phone'=>$result->phone,
'is_signed_in' => TRUE );
$this->session->set_userdata('logged_in', $session_array);
redirect('./dashboard');
}
else
{
$this->session->set_flashdata('error', 'Email Address or password mismatch');
$this->index();
}
}
}
}
Model
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Signin_model extends CI_Model
{
// This function used to check the login credentials of the user
function sign_in_me($email, $password)
{
$this->db->select('*');
$this->db->from('user_login');
$this->db->where('email', $email);
$this->db->where('isdeleted', 0);
$query = $this->db->get();
$user = $query->row();
if(!empty($user)){
if(verifyHashedPassword($password, $user->password)){
return $user;
} else {
return array();
}
} else {
return array();
}
}
function get_user_info_id($user_id){
$this->db->select('*');
$this->db->from('user_login');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query->row();
}
}
Want to redirect
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
require APPPATH . '/libraries/FrontController.php';
class Dashboard extends FrontController {
public function __construct(){
parent::__construct();
$this->load->helper('cias');
$this->load->model('home_model');
$this->load->model('signin_model');
$this->is_signed_in();
}
public function index(){
$this->load->view("front/dashboard", $data);
}
function signout() {
$this->session->sess_destroy ();
redirect ( 'signin' );
}
}
I'm testing a page protected with IsGranted('ROLE_ADMIN') annotation. How do I make a request that simulate an autheticated user with role 'ROLE_ADMIN'?
I used this
<?php
namespace App\Tests\Controller;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* Test Page controller
*/
class PageControllerTest extends WebTestCase
{
private $client = null;
public function setUp()
{
$this->client = static::createClient();
}
public function testHomePage()
{
$client = static::createClient();
$client->request('GET', '/');
$this->assertTrue($client->getResponse()->isRedirect('/login'));
}
public function testHomePageSuccess()
{
$this->logIn();
$this->client->request('GET', '/');
$this->assertEquals(200, $this->client->getResponse()->getStatusCode());
}
private function logIn()
{
$session = $this->client->getContainer()->get('session');
$firewallName = 'main';
$firewallContext = 'main';
$token = new UsernamePasswordToken('admin', null, $firewallName, ['ROLE_ADMIN']);
$session->set('_security_'.$firewallContext, serialize($token));
$session->save();
$cookie = new Cookie($session->getName(), $session->getId());
$this->client->getCookieJar()->set($cookie);
}
}
I am using Yii auth extension for user's authentication wise can get access.
In initial level of auth module only describe give operations,assignment,task according to user role.
I want give task according to bizrule at assign by user can access(update,listing,delete) own data.
I want to change one file for apply bizrule
AuthFilter.php
class AuthFilter extends CFilter
{
public $params = array();
public $enableBizRule = true;
public $enableBizRuleData = true;
protected function preFilter($filterChain)
{
$itemName = '';
$controller = $filterChain->controller;
$user = Yii::app()->getUser();
if (($module = $controller->getModule()) !== null) {
$itemName .= $module->getId() . '.';
if ($user->checkAccess($itemName . '*')) {
return true;
}
}
$itemName .= $controller->getId();
//print_r($itemName);
if ($user->checkAccess($itemName . '.*')) {
return true;
}
$itemName .= '.' . $controller->action->getId();
if ($user->checkAccess($itemName, $this->params)) {
return true;
}
if ($user->isGuest) {
$user->loginRequired();
}
throw new CHttpException(401, Yii::t('yii', 'You are not authorized to perform this action.'));
}
}
http://www.yiiframework.com/extension/auth/
http://www.cniska.net/yii-auth/en_us/auth/assignment/index
I have follow yii site to work with upload image, code here:
class ItemController extends CController
{
public function actionCreate()
{
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
{
$model->image->saveAs('path/to/localFile');
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
}
}
however how can I rename file by currentdate+filename.png and upload to path,also I need code for update and delete.
thankyou very much
I have resolve this problem:
public function currentDate(){
$date = date('m-d-Y-h-i-s', time());
return $date;
}
public function actionCreate(){
$model = new News();
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$uploadedFile = CUploadedFile::getInstance($model, 'images');
$fileName = "{$this->currentDate()}-{$uploadedFile}";
$model->images = $fileName;
if($model->save()){
$uploadedFile->saveAs("upload/".$fileName);
$this->redirect(array('news/index'));
}else{
$model = new News();
$this->render('create',
array('model' =>$model,
'result'=>'insert new fail !',
));
}
}else{
$this->render('create',
array(
'model'=>$model,
));
}
}
public function actionCreate()
{
$model=new News;
if(isset($_POST['News']))
{
$model->attributes=$_POST['News'];
$name = $_FILES['News']['name']['images'];
$filename = pathinfo($name, PATHINFO_FILENAME);
$ext = pathinfo($name, PATHINFO_EXTENSION);
$newName = date("m-d-Y-h-i-s", time())."-".$filename.'.'.$ext;
$model->images = CUploadedFile::getInstance($model,'images');
if($model->save())
$fullImgSource = Yii::getPathOfAlias('webroot').'/upload/'.$newName;
$model->images->saveAs($fullImgSource);
$model->images = $newName;
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array('model'=>$model,));
}
To rename the file after upload and update in DB, try this code.
$model=new Item;
if(isset($_POST['Item']))
{
$model->attributes=$_POST['Item'];
if($model->save())
{
$imageName = #$_FILES["MenuItems"]["name"]["image"];
$uniqueName = (imageName . $model->id) . '.' . (end(explode('.', $imageName)));
$model->image=CUploadedFile::getInstance($model,'image');
$model->image->saveAs('path/to/localFile/'.$uniqueName);
$model->image = $uniqueName;
$model->save();
// redirect to success page
}
}
$this->render('create', array('model'=>$model));
you can use this method that I had created later to upload file and change its name before upload it :
public static function createAttach($model, $imageAttrName) {
$model->$imageAttrName = CUploadedFile::getInstance($model, $imageAttrName);
$fecha = date('YmdHms');
if ($model->$imageAttrName) {
$attach_src = Yii::app()->basePath . '/../upload/' . $fecha.'.'.$model->$imageAttrName->getExtensionName(); //. '_' . $model->$imageAttrName;
$model->$imageAttrName->saveAs($attach_src);
$model->$imageAttrName = $fecha.'.'.$model->$imageAttrName->getExtensionName();// . '_' . $model->$imageAttrName;
}
}
I am trying to construct an object from a stored procedure will yii.
http://www.yiiframework.com/doc/api/1.1/CDbDataReader
I am unsure how to use the function $dataReader->readObject('image', $image);
to construct an object- anyone any ideas if this is the correct way or if this is very slow way of constructing objects
function __construct($image) {
print "In BaseClass constructor\n";
}
public static function getImageFromAliasTitle($alias_title)
{
// $alias_title =Utils::checkEnteredData($alias_title);
$connection = Yii::app()->db;
$command = $connection->createCommand("CALL get_associated_image_detail(:in_image_alias_title, :in_image_visible, :in_image_approved, :in_album_visible, :in_album_approved)");
$command->bindParam(":in_image_alias_title",$alias_title,PDO::PARAM_STR);
$command->bindValue(":in_image_visible",'1',PDO::PARAM_STR);
$command->bindValue(":in_image_approved",'Yes',PDO::PARAM_STR);
$command->bindValue(":in_album_visible",'1',PDO::PARAM_STR);
$command->bindValue(":in_album_approved",'Yes',PDO::PARAM_STR);
try{
$dataReader = $command->query();
if($dataReader->count() >0)
{
$image = $dataReader->read();
}
$dataReader->readObject('image', $image);
// $image = $dataReader->read();
$dataReader->nextResult();
$album = $dataReader->readAll();
$dataReader->nextResult();
$tag = $dataReader->readAll();
$dataReader->nextResult();
$user_image = $dataReader->readAll();
$dataReader->close();
}
catch(Exception $e){
Yii::log('', CLogger::LEVEL_ERROR, 'Message Here...');
}
return $image;
}
What about this:
foreach($row as $dataReader->readAll()){
echo $row["image"];
}
if It does not help then try to print:
print_r($dataReader->readAll());