Laravel 5, self reference hasone not work in blade - laravel

All
I have Invoice model, and self reference
\\Invoice Model
public function parentInvoice()
{
return $this->hasOne('App\Invoice', 'id', 'parent_invoice_id');
}
for test in web.php it's work
Route::get('self', function () {
$parent = Invoice::find(132);
$children = $parent->parentInvoice->invoice_date;
echo $children;
// 2018-06-08 - it's work
});
but on blade don't work :( Why?
not work! - <b>Date:</b> {{$invoice->parentInvoice->invoice_date)}} <br /><br />
it's work - <div class="header">Korekta faktury nr {{ $invoice->invoice_date
}}</div>
Error: Trying to get property of non-object
Please help :(
This is my function on Invoice model:
private function generateCreditnoteInvoiceChangeData()
{
$config = InvoiceConfig::find(1);
$pdf = \PDF::loadView(
'pdf.creditnote_invoice_change_data',
array(
'config' => $config,
'invoice' => $this
)
);
return $pdf;
}

Related

ErrorException thrown with message "Trying to get property 'user' of non-object

I am using relationship in my laravel project. I am trying to show my post and replies. But i keep getting this error. I've tried various solution but none of them worked. Can anyone help me?
Post model:
protected $fillable = [
'title', 'content', 'category_id' , 'slug', 'user_id',
];
public function user1()
{
return $this->belongsTo('App\User');
}
public function replies()
{
return $this->hasMany('App\Reply');
}
Reply model:
protected $fillable = ['content','user_id','posts_id'];
public function post(){
return $this->belongsTo('App\Post');
}
public function user()
{
return $this->belongsTo('App\User');
}
PostController:
public function shro($slug)
{
$pst= Post::where('slug',$slug)->first();
return view('posts.show')->with('p', $pst);
}
show.blade.php
<div class="panel panel-default">
<div class="panel-heading">
<img src="/uploads/avatars/{{ $p->user->avatar }}" alt="" width="70px" height="60px">
<span>{{ $p->user->name }}, <b>{{ $p->created_at->diffForHumans() }}</b></span></br>
</div>
$p, or $pst (confusing variable names) is null, and this is because ->first() can return null. Do you have a Post record in your database that matched slug?
Rule of thumb; never assume something exists.
Add some logic to ensure the Post exists before trying to access a property of it:
$post = Post::where("slug", $slug)->first();
if(!$post){
abort(404);
}
return view('posts.show')->with('post', $post);
// OR
$post = Post::where("slug", $slug)->findOrFail(); // or firstOrFail();
return view('posts.show')->with('post', $post);
Also, check your $post->user:
#if($post->user)
<img src="/uploads/avatars/{{ $post->user->avatar }}" width="70px" height="60px"/>
<span>{{ $post->user->name }}, <b>{{ $post->created_at->diffForHumans() }}</b></span></br>
#endif
If $post->user returns null, you'll have a similar error.
You can eager load the user with it's relative post at once by doing :
//...
$pst= Post::where('slug',$slug)->with(['user1'])->first();
//...

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

How to pass variable from blade to LARAVEL commands

I need to pass user_id from blade to routes, and then use the variable into a laravel command. How can I do?
lista_lavori.blade.php
<div class="box-tools">
<i class="fa fa-print"></i>
</div>
web.php - route
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport');
return back();
});
StampaSingoloReport.php - Commands
public function handle()
{
// static id i need to change this dinamically
$id = 5;
$utente = \App\User::where('id',$id)->get();
//invio email per avvertire l'utente
$data = array('utenti'=>$utente);
Mail::send('mail.invioMailReportLavoriSingoli', $data, function($message) {
$message->to('rubertocarmine94#gmail.com', 'Admin Risorse Umane') ->subject('Email da piattaforma BancaStatoHR') ;
$message->from('rubertocarmine94#gmail.com') ;
});
}
You can pass an array to call() method like
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport',[
'id' => $id
]);
return back();
});
Now in your handle method, you can access these arguments like
protected $signature = 'StampaSingoloReport:stampasingoloreport { id } ' ;
function handle(){
$this->argument('id');
// your code
}
Hope this helps

How do I display adodb data in Codeigniter in my view?

I have this code in my model in codeigniter:
<?php
class User_model extends Model {
function User_model()
{
parent::Model();
}
function get_data()
{
$pages = false;
// Get the pages from the database using adodb if needed
$this->adodb->connect();
$recordSet = $this->adodb->execute('SELECT id, genreID, artist, albumName FROM album' );
if ( ! $recordSet )
{
log_message( 'error', 'Error connecting to the database' );
log_message( 'debug', $this->adodb->getErrorMsg());
}
else
{
unset( $this->pages );
while (!$recordSet->EOF)
{
$pages[] = array(
'id' => $recordSet->fields[0],
'genreID' => $recordSet->fields[1],
'artist' => $recordSet->fields[2],
'albumName' => $recordSet->fields[3]
);
$recordSet->MoveNext();
}
$this->pages = $pages;
}
$this->adodb->disconnect();
}
}
?>
I have this in my controller:
<?php
class Welcome extends Controller {
function Welcome()
{
parent::Controller();
}
function index()
{
//
$this->load->model('User_model');
$data['query'] = $this->User_model->get_data();
$this->load->view('welcome_message',$data);
}
}
What I cannot do is get my model results into my view. There is no result() object because I used adodb so this:
<?php foreach($query->result() as $row): ?>
<p>
<?=$row->albumName;?>
</p>
<?php endforeach; ?>
gets me an error.
What do I put in my view to get the query results of my model. I know the model works because I can echo $recordSet->fields[3]; from the model and see the album name.
Thank you for any help.
edit: I don't understand why my get_data() call in my view returns nothing.
For one you are not returning anything from get_data so that will cause $query to be null. Also you shouldn't be executing the query in the view because view content should not be handling data layer operations, also you've already disconnected from the db.

cakephp validation response returning data to controller

Hi i have made a custom validation in the model. How can i access the result($visitor) from this in the controller?
model:
<?php
class Visitors extends AppModel
{
var $name = 'Visitors';
var $validate = array(
'xxx' => array(
'rule' => array('checkxxx'),
'message' => 'yyy.'
)
);
function checkIxxx($check){
$visitor = $this->find('first', array('conditions' => $check));
return $visitor;
}
}
?>
in my controller i want this:
function start() {
$this->Visitors->set($this->data);
if($this->Visitors->validates())
{
if($this->Visitors->xxx->type == 'value') //this is a value from the $visitor array in the model**
{
//do something
}
}
is this possible?
Updated to be a relevant answer, apologies.
//Model
var myField = 'invalid';
function myValidation($var){
if($var === true){
// Passed your validation test
$this->myField = 'valid';
}else{
$this->myField = 'invalid';
}
}
// Controller
$this->Model->set($this->data);
$this->Model->validates($this->data);
if($this->Model->myfield == 'valid'){
// Field has passed validation
}
You will want to use
$this->Model->invalidFields()
PS: You dont follow cake conventions
the model should be "Visitor" (singular)

Resources