Object values not being passed - mysql

I am using Laravel 5.6 and having an issue passing data to my blade file.
BlogController:
namespace App\Http\Controllers;
use App\Mail\Practice;
use App\Mail\Mailable;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Session;
class BlogController extends Controller
{
public function getSingle($slug){
// Fetch from the DB based on Slug --first stops after one, get pulls everything
$post = Post::where('slug', '=', $slug)->first();
print_r($slug);
// return the view and pass in the post object
return view('blog.single')->withPost($post);
}
}
single.blade.php:
#extends('main')
#section('title', "| $post->title")
#section('content')
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1>{{ $post->title}}</h1>
<p>{{ $post->body }}</p>
</div>
#stop
I verified the name and spelling in the DB (MySQL.) If I dd($slug) or print_r($slug) the results are correct.
However, if I do the same but use $title or $body it returns the error
Trying to get property of non-object (View: /Users/jesseburger/myproject/resources/views/blog/single.blade.php)
I have been able to verify its pulling an empty array by using print_r($post) but can't figure out why.
print_r($post) yields:
Illuminate\Database\Eloquent\Collection Object ( [items:protected] => Array ( ) )
Current route:
Route::get('blog/{slug}', [
'as' => 'blog.single',
'uses' => 'BlogController#getSingle'
])->where('slug', '[\w\d\-\_]+');

Your return statement is incorrect, you need to change this line:
return view('blog.single')->withPost($post);
To this, it should resolve your issue.
return view('blog.single')->with('post', $post);

First you are debugging your slug not your post. Try to debug your post to see if it was found. You are getting that error because the post doesn't exist at all. Abort if it doesn't exist.
if(!$post){
abort(404);
}

Related

json_decode () breaking when called directly in the Laravel Blade template - (expects string, object given)

I have a Laravel Results model that returns some data from a database to a blade view from a 'results' table. One of the columns is called properties which is of a json datatype and it stores data similar to the following:
{
"clubs": [
{
"id": 1741008,
"name": "BanterburyFC",
"wins": "0"
},
{
"id": 17844730,
"name": "es ticazzi",
"wins": "1"
}
]
}
The index controller gets the results from the getResults() function which returns an array of values such as match_id, home_team_goals, away_team_goals & properties - the properties (which is of a json datatype in the MySQL database is looped through on the frontend & I do the json_decode directly in the blade template, however it gives me the following error.
htmlspecialchars() expects parameter 1 to be string, object given (View: /Users/myname/Projects/myapp/resources/views/dashboard.blade.php)
Weirdly when I run the json_decode() on the same data in the controller before I pass this into the view it works fine and creates an object as expected. However for some reason when I attempt to run the json_decode directly inside the blade view it returns the Error Exception above.
What's wrong?
Controller logic
public function index()
{
$user = auth()->user();
$data = [ 'results' => Result::getResults($user->properties) ];
// var_dumping so I can check the data before it is passed to the blade view
var_dump($data['results'][0]->properties); // returns string - looks fine & this doesn't return any errors
var_dump(json_decode($data['results'][0]->properties)); // returns object - looks fine & this doesn't return any errors either
return view('dashboard', $data);
}
Blade view/template
#foreach ($results as $result)
{{ json_decode($result->properties) }} <!-- the line causing the problem -->
{{ json_decode($result->properties, true) }} <!-- this also fails -->
#endforeach
Using PHP 8.x & Laravel 8.x
In the Laravel blade {{}} is equal to echo so it accept string not an object. It uses htmlspecialchars internally for XSS protection against injection. So when you are trying to do {{ json_decode($result->properties) }}, it is throughing the error. Instead you can use #php ... #endphp directives.
#foreach ($results as $result)
#php $p = json_decode($result->properties); #endphp
#endforeach

Laravel-generated email not formatting HTML correctly

I am struggling with email formatting issue, with Laravel.
I get the email content (HTML) from the database, which doesn't really matter, but then quotes get added around, the format is wrong and my email looks like this:
Here is my code, thanks a lot for your help!
I tried with
'content' => htmlspecialchars($content)
and
'content' => htmlentities($content)
but none work, and for the blade file:
<div>
{{!!$content!!}}
</div>
gives me an error. I also tried
<div>
{{{$content}}}
</div>
(also an error of unexpected character) and
<div>
{{$content}}
</div>
(here was the original one)
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cookie;
class InsuranceEmail extends Mailable
{
use Queueable, SerializesModels;
protected $attacheddoc;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($attacheddoc)
{
$this->attacheddoc=$attacheddoc;
}
/**
* Build the message.rubr
*
* #return $this
*/
public function build()
{
$name = Auth::user()->nom . " " . Auth::user()->prenom;
$sqlContent="SELECT texte from blabla";
$content = DB::connection('blabla')->select( DB::connection('blabla')->raw($sqlContent))[0]->texte;
$content = str_replace('#memberName#', $name, $content);
$content = str_replace('"', '', $content); //I tried this, without any hope ;)
return $this->from('contact#blabla.net')
->markdown('emails.blabla')->with([
'title' => "Email onject",
'memberName' => $name,
'content' => $content,
])
->attach($this->attacheddoc, array(
'as' => 'attacheddoc.pdf',
'mime' => 'application/pdf'));
}
}
I tried a few things to try and fix my email displaying incorrectly. In the end clearing my view cache solved my problem, which I hadn't seen anyone else suggest. This most likely wasn't your issue here but I will include it in my answer to hopefully help anyone else with my issue.
Publish the Laravel email views
php artisan vendor:publish --tag=laravel-mail
Make sure there are no indents in your html views
resources/views/vendor/mail/html
Make sure to escape any html inserted via variable
{!! $content !!}
Clear cached views
php artisan view:clear
As per Laravel Documentation:
By default, Blade {{ }} statements are automatically sent through
PHP's htmlspecialchars function to prevent XSS attacks. If you do not
want your data to be escaped, you may use the following syntax:
Hello, {!! $name !!}.
Reference:
Laravel -> Blade Templates -> Displaying Unescaped Data
In your emails.blabla view us elike this it will escape HTML element
{{{ $content }}}
or try
{!! $content !!}

i have inserted data in databse but not knowing how to show in laravel

I am getting this error
Missing required parameters for [Route: service.show] [URI: service/{service}].
public function show($id)
{
$service = Service::find($id);
return view('service.show')->withPost($service);
//
}
controller
i have one blade file to show.
Route file .
Route::resource('service', 'ServiceController');
Route::get('service/{id}', 'ServiceController#show');
Is this route correct
It is easier when you read Laravel Documentation.
This are some teachers of Laravel Coders Tape and Brad Traversy. You can learn from them from scratch
You can do it this way.
CONTROLLER
public function show($id)
{
$service = Service::find($id);
return view('service.show', compact('service'));
//
}
ROUTE
Route::resource('/service', 'ServicesController');
BLADE / VIEW
<div>
{{$service->id}}
</div>
public function show($id)
{
$service = Service::find($id);
return view('service.show')->with('service', $service);
}
In your blade,
<div>
{{ $service}}
</div>
Just use 2 curly braces {{ }} and put it inside the variable you use. In this example i used service
You need to call the show route with service id in parameter.
Route::get('service/{id}', 'ServiceController#show')->name('service.show');
<a href="{{ route('service.show', $id)">Show<a/>
If you wanna redirect to that route:
return \Redirect::route('service.show', $id);
Route
I would give the route a unique name, so you can easily generate links.
Route::name('service_info')->get('/service/{id}', 'ServiceController#show');
Controller
I think you need to use $request.
I added a check for 404 issues, but you could also check that in a middleware.
public function show(\Illuminate\Http\Request $request)
{
$service = Service::find($request->id);
if ($service === null) {
abort(404, "service not found");
}
return view('show', [
'service' => $service
]);
}
Blade
And in the blade you can use the service with {{}}
<div>
{{$service}}
</div>
Or if 'Service' has attributes like 'name' or 'id' and you want to use them:
<div>
{{$service->id}}: {{$service->name}}
{{$service->id.': '.$service->name}}
</div>
Both are possible.

Want to get maximal value, but query doesn't work

I try to program a query in Yii2, which shows me the highest value of the database. Unfortunately, I get error message:
"Call to a member function all() on string"
How to patch this problem?
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller
{
public function actionIndex()
{
$query = Country::find();
$countries = $query->select('population')->max('population')
->all();
return $this->render('index', [
'countries' => $countries,
]);
}
}
?>
You can use this
$query = Country::find();
$countries = $query->select('population')->max('population');
Also you can use
$query = Country::find();
$countries=$query->select('max(population) as `population`')->one();
It will help you :)
You have put as 'population' or other field name in table to assign value in second query.
According to your code example, you are calling all() on the result of max(), which according to the error message is returning a string.
max() is returning the maximum value, so you probably just need to drop ... ->all().
Try this:
$countries = $query->select('population')->max('population');

Pass data from a query to a view

The problem I have is that I do not know how I can use the data of a query in a view if someone can give me a serious idea, the form I use is this but it gives me an error:
My Controller:
public function edit($id){
$datosProfesor = DB::table('profesor')->where('id', $id)->get();
$institucionDB = DB::table('institucion')->get();
$datos = array('datosProfesor' => $datosProfesor, 'institucionDB' => $institucionDB);
return view('profesorView/editarProfesor', $datos);
}
My view:
<div class="form-group">
<h4>Nombre</h4>
<input type="text" name="nombre_profesor" id="nombre_profesor" class="form-control" placeholder= 'Nombre' value="{{$datosProfesor['id']}}">
</div>
The error that appears to me is this:
Undefined index: id (View: /var/www/html/Konecte/resources/views/profesorView/editarProfesor.blade.php)
The get() method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object. You may access each column's value by accessing the column as a property of the object:
foreach ($datosProfesor as $profesor) {
echo $profesor->id;
}
If you want to get a single result then you can use find() method as:
$datosProfesor = DB::table('profesor')->find($id);
which is a short form of:
$datosProfesor = DB::table('profesor')->where('id', $id)->first();
Just one more tip for you that you can use PHP's compact() method for creating array containing variables and their values. So that you can get rid of line
$datos = array('datosProfesor' => $datosProfesor, 'institucionDB' => $institucionDB);
Your final code will look as:
public function edit($id){
$datosProfesor = DB::table('profesor')->find($id);
$institucionDB = DB::table('institucion')->get();
return view('profesorView/editarProfesor', compact('datosProfesor', 'institucionDB'));
}