upload image to content in Yii - yii

I have 2 tables, postimage and post. Postimage has fields post_id, id and image. I need to create upload form of the image and show it when content created. This image should be lincked to the content(though post_id field). Uploading form appears but images don't uploading. I tried such a way:
class PostImageController extends Controller
{
public $layout='//layouts/column2';
/**
* #return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('#'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new PostImage;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PostImage']))
{
$model->attributes=$_POST['PostImage'];
$model->image=CUploadedFile::getInstance($model,'image');
if($model->save())
$path=Yii::getPathOfAlias('webroot').'/images/'.$model->image->getName();
$model->image->saveAs($path);
//$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['PostImage']))
{
$model->attributes=$_POST['PostImage'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* #param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('PostImage');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new PostImage('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['PostImage']))
$model->attributes=$_GET['PostImage'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* #param integer $id the ID of the model to be loaded
* #return PostImage the loaded model
* #throws CHttpException
*/
public function loadModel($id)
{
$model=PostImage::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* #param PostImage $model the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='post-image-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
PostImage model:
<?php
/**
* This is the model class for table "PostImage".
*
* The followings are the available columns in table 'PostImage':
* #property integer $id
* #property string $image
* #property integer $post_id
*
* The followings are the available model relations:
* #property Post $post
*/
class PostImage extends CActiveRecord
{
/**
* #return string the associated database table name
*/
public $image;
public function tableName()
{
return 'PostImage';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//array('image', 'required'),
array('post_id', 'numerical', 'integerOnly'=>true),
array('image', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, image, post_id', 'safe', 'on'=>'search'),
array('image', 'file', 'types'=>'jpg, gif, png'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'post' => array(self::BELONGS_TO, 'Post', 'post_id'),
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'image' => 'Image',
'post_id' => 'Post',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('image',$this->image,true);
$criteria->compare('post_id',$this->post_id);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return PostImage the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
And this is view of the form:
<?php
echo CHtml::form('','post',array('enctype'=>'multipart/form-data'));
echo CHtml::activeFileField($model, 'image');
echo CHtml::endForm();
?>

Related

Laravel Default validation message wouldn't appear

I am developing a Laravel backend API. I am trying to build an API that will accept two fields which are name and email with validation.
Here is my controller file:
public function register(RegisterUserRequest $request)
{
// retrieved validated user
$validated = $request->validated();
}
Here is my RegisterUserRequest file:
class RegisterUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required|email:rfc,dns',
];
}
}
I am trying to pass the invalid email format to the backend but the error message not appearing:
I had already set my header to Accept:application/json in my postman.
Is anyone know how to resolve the problem? Really appreciated!
Thanks.

Issue With Laravel 8 Auth Email Verification

I'm Using Laravel 8.x And i'm trying to make login/register With Email verification
I followed Some Tutorials,Blogs but didn't get desired output
I want:-
Whenever User Register themselve An Verification Email must send to there email
(Email Is Sent but not able to verify by that url so i follow some laracast blog by that i'm able to verify by that verification url)
but the issue is if i didn't verified my self i'm still able to login into my application
Here Is Codes
HomeController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['auth','verified']);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
','--------------------------------------------------------------------------
',' Register Controller
','--------------------------------------------------------------------------
','
',' This controller handles the registration of new users as well as their
',' validation and creation. By default this controller uses a trait to
',' provide this functionality without requiring any additional code.
','
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'contact' => ['required','min:10'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required','string','min:8','confirmed','regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{6,}$/'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'contact' => $data['contact'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
Veification Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Verified;
use Illuminate\Auth\Access\AuthorizationException;
use App\Models\User;
class VerificationController extends Controller
{
/*
|--------------------------------------------------------------------------
| Email Verification Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling email verification for any
| user that recently registered with the application. Emails may also
| be re-sent if the user didn't receive the original email message.
|
*/
use VerifiesEmails;
/**
* Where to redirect users after verification.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
// $this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:6,1')->only('verify', 'resend');
}
public function verify(Request $request)
{
// if ($request->route('id') != $request->user()->getKey()) {
// throw new AuthorizationException;
// }
$user = User::find($request->route('id'));
auth()->login($user);
if ($request->user()->hasVerifiedEmail()) {
return redirect($this->redirectPath());
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect($this->redirectPath())->with('verified', true);
}
}
Route
Auth::routes(['verify' => true]);
Route::group(['prefix'=>'user', 'middleware' => 'auth'],function(){});

How to show content for the users using CGridView?

I have a page with the list of categories on my site and I want to show them using Cgridview as right now they displayed with CListView. I'm using Yii 1.1. I see that CGridView used only if you want to manage content but is it possible to use it if you want to show it, on the index pages?
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'status',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
You can used this code for your cgridview
Categories Model
File Path : protected/model/categories.php
Categories.php
<?php
/**
* This is the model class for table "categories".
*
* The followings are the available columns in table 'categories':
* #property integer $id
* #property string $title
* #property string $status
*/
class Categories extends CActiveRecord
{
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'area';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('title, status', 'required'),
array('status', 'numerical', 'integerOnly'=>true),
array('title', 'length', 'max'=>255),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, title, status', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'id' => 'ID',
'title' => 'Title',
'status' => 'Status'
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* #return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search()
{
// #todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('title',$this->title,true);
$criteria->compare('status',$this->status);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* #param string $className active record class name.
* #return Area the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}
Categories Controller
File Path : protected/model/CategoriesController.php
CategoriesController.php
<?php
class CategoriesController extends Controller
{
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* #return array access control rules
* #access Public
*/
public function accessRules()
{
return array(
array('allow',
'actions' => array('index'),
'users' => array('*'),
),
array('deny',
'users' => array('*'),
),
);
}
public function actionIndex()
{
$model = new Categories();
$model->unsetAttributes();
if(isset($_REQUEST['Categories']))
$model->attributes = $_REQUEST['Categories'];
$this->render('index',array('model'=>$model));
}
}
Categories View File
File Path : protected/view/index.php
index.php
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'title',
'status',
array(
'class'=>'CButtonColumn',
),
),
)); ?>
you can add your design in index.php file.
refere this link for design

PHPStorm property-read for Yii model relations

How can I do this in PHPStorm so hinting works correctly when calling the model() method?
For instance:
/**
* #property-read \Stores $store
*/
class Items extends CActiveRecord
{
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function relations()
{
return array('store' => array(self::BELONGS_TO, 'Stores', array('store_id' => 'id')),
}
}
$items = new Items;
$items->store; // PHPStorm type hints this correctly
Items::model()->store; // PHPStorm does NOT type hint correctly.
Model above minimalist for focus of this post.
You just have to 'tell' PhpStorm what this method returns.
/**
* #param $className
* #returns Items
*/
public static function model( $className = __CLASS__ ) {
return parent::model( $className );
}

Laravel "auth controller not found" exception

I am making admin panel in LARAVEL4.2.*. I make the controller in "admin" folder and also a view in views "admin" folder. My controller code is
namespace admin;
class AuthController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
and my routes coding is:
Route::get('admin/login', array('as' => 'admin.login', 'uses' => 'App\Controllers\Admin\AuthController#getLogin'));
I have also tried "composer update" and "composer dump-autoload" above 50 times. My url is localhost/laraveltest/public/admin/login.
You defined your namespace as admin, therefore you have to use this also in your routes:
Route::get('admin/login', array('uses' => '\admin\AuthController#getLogin'));