Finding where values come to the $model - yii2

I changed the login page layout and got error that $model is undefined variable in Yii.
How can I find where values come to the $model?
Where is the model variable declared?
Error page:

Inside the controllers directory you can find the SiteController.php controller file. In this controller class you can find the below index method. For example
public function actionIndex() {
$model = new YourModelClassName(); //your model file class name replace here
return $this->render('index', ['model' => $model]);
}

Related

(1/1) FatalErrorException Call to a member function all() on null in laravel 5.4

4 and i have a form when submitted i want to validate its fields, what happened is when i submit the form this is what it gets
(1/1) FatalErrorException
Call to a member function all() on null
This is my code below
$validator = app('validator')->make($this->request->all(),[
'postTitle' => 'required',
'postContent' =>'required']);
In laravel 5.2 this validator works well but in laravel 5.4 it returns null
can someone help me figured this thing out?
Any help is muchly appreciated. TIA
this is my full code
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use Illuminate\Http\Request;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
protected $request;
// Intialize request instance
public function __contruct(Request $request){
$this->request = $request;
}
public function addPosts(Request $request){
//validate posts
echo "test";
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
}
Seems an issue with the method injection (in the constructor) or something.
You may try creating the request object on the local(addPosts()) function.
Please try below alternative solution.
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
public function addPosts(Request $request){
//validate posts
$reqeust = new \Illuminate\Http\Request;
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
// REST OF THE CODE GOES HERE...
}
Given the information you gave, I will demonstrate you how to validate a request properly in Laravel 5.4
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
if ($validator->fails()) {
return redirect('your.view')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
This will successfully validate the request for you wherever need be. If the validation fails, you will be forwarded to your view with the according errors.
Make sure you use Validator; on top of your file.
For more information, you can read up on https://laravel.com/docs/5.4/validation

Save default values in Yii2 not working

I want to save the this following datetime while update or create so I wrote this in rules()
['createdon','default','value'=>date('Y-m-d H:i:s'),'on'=>'insert' ],
['updatedon','default','value'=>date('Y-m-d H:i:s'),'on'=>'update' ],
and I declare scenario in create and update functions as
public function actionCreate()
{
$model = new JobFunctionRole();
$model->scenario = 'insert';
....
....
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update';
...
...
}
While create datetime stores perfectly.but in update its not stores.Whats the issue??Anybody?
You directly use _form
<?= $form->field($model, 'createdon')->hiddenInput('value'=>date("Y-m-d")])->label(false) ?>
These are validators for user input. You probably are looking for TimestampBehavior:
http://www.yiiframework.com/doc-2.0/yii-behaviors-timestampbehavior.html
The TimestampBehavior config should be added to an ActiveRecord model. Not the controller.

Difference between afterSave and a Event in yii2?

I wanted to send an email to admin when a new user registers. I think i can do it using two ways. one way is to use events and other is by using afterSave.
By using Events
Controller code
public function actionCreate()
{
$model = new Registeration();
if ($model->load(Yii::$app->request->post()))
{
if($model->save())
{
$model->trigger(Registeration::EVENT_NEW_USER);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Model code
const EVENT_NEW_USER = 'new-user';
public function init(){
$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
}
public function sendMail($event){
// code
}
I can do the same using the afterSave method
Model code
public function afterSave($insert)
{
//code
return parent::afterSave($insert);
}
So is there any difference between the two methods? Which one is better using Events or afterSave() ?
I am new to Yii,
It depends on what you are trying to implement.
When you use afterSave email will be sent on updates also.
So event would be a better choice to your problem.
Thanks & Regards
Paul P Elias

How to dynamically return API JSON from the database and store JSON in MySQL in Laravel 5.1

I am currently developing an api for my site to work with google maps. I have successfully developed an api with help from the community. But it only outputs a single page. I need it to be dynamic, because results will be based off of input from the user. As it stands my controller looks like this
<?php
namespace App\Http\Controllers;
use App\Post;
use App\Http\Requests;
class ApiController extends Controller
{
public function index() {
$results = [];
foreach (Post::all() as $post)
{
$results[] = [
'id' => $post->id,
'marketname' => $post->subtitle,
];
}
return ['results' => $results];
}
}
but this isn't dynamic.
I was thinking of copying my search and modifying it. it looks like this
<?php
namespace App\Http\Controllers;
use App\Jobs\TagIndexData;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\Video;
use App\Tag;
use App\Http\Controllers\Controller;
class TagController extends Controller
{
public function index(Request $request)
{
$query = $request->get('q');
$posts = Post::where('title', 'LIKE', "%{$query}%")
->orwhere('subtitle', 'LIKE', "%{$query}%")->get();
$videos = Video::where('title', 'LIKE', "%{$query}%")
->orwhere('subtitle', 'LIKE', "%{$query}%")->get();
$tag = $request->get('tag');
$data = $this->dispatch(new TagIndexData($tag));
$layout = $tag ? Tag::layout($tag) : 'tags.layouts.index';
return view($layout, $data)->withPosts($posts)->withVideos($videos);
}
}
But I don't understand how to store json in mysql nor how to query it and output it Any help would be greatly appreciated.
To be clear on what I want. I want a person to enter their zipcode or address and then return a google map populated with markers indicating nearby events.
I am trying to modify a tutorial I did using a farmers market api mashed up with googles. Part of the javascript looks like this
accessURL="http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=" + userZip/address;
where userZip/address is input that I want to use to populate the google map
any advice on how I should structure this is welcomed
Returning JSON from the controller is pretty straight forward. Simply return the collection:
public function index() {
$posts = Post::all();
return $posts;
}
Or if you only need to return certain fields, use select():
public function index() {
$posts = Post::select(['id', 'subtitle as marketname'])->get();
return $posts;
}

How to eager load relations for single eloquent object?

I have this Comment model with belongs to relationship.
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
While in my controller:
public function store(Request $request)
{
$comment = $this->dispatch(
new StoreCommentCommand($request->body, Auth::user()->id, $request->post_id)
);
return $comment;
}
When I return the $comment I also want nested user object, how can I do that?
You need to use the with() on Builder object, whereas currently you are using on eloquent object. This will be your working code.
return Comment::with('user')->where('id', $comment->id)->first();
Just eager load it...
return $comment->with('user');
In case anyone stumbles upon this, you can just assign the user to the comment before returning it.
$comment->user = Auth::user()
return $comment
The with eager-loading function isn't needed here.