Laravel - Display Array/String Object in view from database - arrays

Data are stored as ["item_1", "item_2"] in database like shown below.
I want to display those data in view blade properly.
Product Model
protected $fillable = ['name', 'prod_id'];
public function models() {
return $this->hasMany(Model::class, 'prod_id');
}
Model Model
protected $fillable = ['model', 'prod_id'];
protected $cat = ['model'=>'array'];
public function model()
{
return $this->belongsTo(Product::class, 'prod_id');
}
Controller - store method
public function create (Request $request, Product $product){
$models = new Model;
{
$model = json_encode(request('models'));
$items->models = $model;
$product->models()->save($models);
}
}
Controller show method
public function show(request $id){
$product = Product::findorfail($id);
$models = Model::with(['model'])->where('prod_id', $product->id)->get();
return view ('show', compact('product', 'models'));
Create View
<input type="checkbox" name="model[]" value="Samsung">
<input type="checkbox" name="model[]" value="Nokia">
<input type="checkbox" name="model[]" value="Apple">
<button>Add Model</button>
I tried show view:
#foreach($models as $model)
{{ json_decode($model->models) }}
#endforeach
It throws
htmlspecialchars() expects parameter 1 to be string, array given
What am I missing.
PS: MySQL does not support json column, so I saved as text column.

you need to do someting like this.
Model Model
protected $fillable = ['models', 'prod_id']; // screenshot says that the field name is "models"
protected $cast = ['models' => 'array']; // the property is $cast no $cat
public function product()
{
return $this->belongsTo(Product::class, 'prod_id');
}
ModelController - store method
public function store (Request $request){
$product = Model::create([
'models' => json_encode($request->models),
'prod_id' => $request->prod_id
]);
return redirect()->back()->with('success', 'created!');
}
public function show(Request $id){
$model = Model::findOrFail($id)->with('product');
return view ('model.show', compact('model'));
}
ProductController show method
public function show(request $id){
$product = Product::findOrFail($id)->with('models'); // the method name is findOrFail() no findorfail
// $models = Model::with(['model'])->where('prod_id', $product->id)->get();
return view ('show', compact('product'));
}
Into the show View
#foreach($product->models as $models)
#foreach(json_decode($models->models) as $model)
{{ $model }}
#endforeach
#endforeach

Your Models Model confuses me a little bit. You seem to have a field name model that's the same as a relationship method name. That means whenever you include that relation, it'd functionally override that property with data from the related table. (I say 'functionally' because you're using dynamic properties, whereas it is actually possible to explicitly tell Eloquent whether you want an attribute or relation without making it guess.)
That said, your $model->models property could be coming back as an array for one of two reasons. The first is that it may be accidentally referring to a relational data-set and not the JSON string you were expecting. The second is you've corrected the protected $cat = ['model'=>'array']; to read protected $cast = ['models'=>'array'];, and it's stepping on your toes now. By casting it to an array, it may be getting automatically get interpreted back into one before you call json_decode on it.
Either way, I'd dd($model->models) to see what it is first.

You need to change your foreach like this:
#foreach($models->models as $model)
{{ json_decode($model) }}
#endforeach
because Your array is like this
{"id":18,"prod_id":22,"models":{"id":22,"user_id":1}}
In here the $models is getting only id and prod_id models is still array so your foreach should be #foreach($models->models as $model)
Sample Code is here:
$arr = '{"id":18,"prod_id":22,"models":{"id":22,"user_id":1}}';
echo '<pre>';
foreach (json_decode($arr->models) as $str){
echo $str;
}

Related

"Array to string conversion" errorr Laravel - Trying to save array to database

Sorry Im new to Laravel and trying to save to the database for the first time. Im trying to save an array to the database but the error "array to string conversion" is appearing. I've tried changing the string value in the migration file to other options but the same error is appearing.
Controller
public function store(Request $request)
{
Myroutes::create([ //posting to acc table
'start' => $request->start,
'end' => $request->end,
'waypoints' => $request->waypoints
]);
return redirect('/');
}
migration
public function up()
{
Schema::create('myroutes', function (Blueprint $table) {
$table->increments('myroute_id');
$table->integer('user_id');
$table->string('start');
$table->string('end');
$table->string('waypoints');
$table->timestamps();
});
}
model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Myroutes extends Model
{
protected $fillable = [
'user_id',
'start',
'end',
'waypoints'
];
}
View
<div id="dynamicInput" class="form-group">
<label>Additional Destinations</label>
<input type="text" name="waypoints[]" class="form-control" autocomplete="on">
</div>
Database table
database-img
protected $casts = [
'theme_setting' => 'array'
];
Just use casting in Model within Class
I used this for laravel 5.8
$array = $request->names;
$array = implode(',', $array);
$request['names'] = $array;
$distribute = User::create($request->all());
You've got an error: 'waypoints' => $request->waypoints won't work, as $request->waypoints is an array, and you can't save an array into a VARCHAR() field. If you implode the input, and convert it to a comma-separated string it should work alright:
`'waypoints' => implode(",", $request->waypoints`)
That being said, this is generally considered a bad idea; consider using relationships between Routes and Waypoints as separate tables, for both clarity and ease of use (especially in retrieving/editing.)
after form submit try to do this :
dd($request->all());
then you will see what will be saved and will see that waypoints is array. You can't save array as string, you must to convert it to string. Variable is array because of :
name="waypoints[]"
it will not be array if you put like this :
name="waypoints"
Your Forminput "waypoints" is an Array!
So you will have to "Convert" it first before you can make the insert

Property [id] does not exist on this collection instance when trying to filter the data with 'comment_id'

what i wants to do is to show the replies that are given to that particular comment on the post.Right now i am able to show the comment to that specific post but the replies are displayed along each comment.
here is the controller part of the code:
public function show($id)
{
$blog = Blog::findOrFail($id);
$comments = Comment::where('blog_id', $id)->get()->all();
$test = Comment::all();
// $comments = Comment::whereIn('blog_id', $id)->get()->all();
$commentReplies = CommentReply::where('comment_id'== $test->id)-
>get();
// $commentReplies = CommentReply::where('comment_id',$blog-
>comment()->id)->get()->all();
return
view('admin/blog/front',compact('blog','comments','commentReplies'));
}
i am saving the refrence to that comment in database in 'comment_id' but when i try to reach the 'comment_id' via $commentReplies it gives me the error of "Property [id] does not exist on this collection instance."
The correct syntax is:
$commentReplies = CommentReply::whereIn('comment_id', $test->pluck('id')->toArray())->get();
You also could use relationships. Define this one in the Comment model:
public function replies()
{
return $this->hasMany(CommentReply::class);
}
Then load comments with replies:
$commentsWithReplies = Comment::with('replies')->get();
And to iterate over comments and replies:
#foreach ($commentsWithReplies as $comment)
{{ $comment->text }}
#foreach ($comment->replies as $reply)
{{ $reply->text }}
#endforeach
#endforeach
You also shouldn't chain ->get()->all(), just use ->get().
And finally, the correct syntax for returning a view is (thanks to #Nikola Gavric):
return view('admin.blog.front', compact('blog', 'comments', 'commentReplies'))

Laravel ->with() can't be shown in blade (Undefined property)

I'm trying to pass an article from my controller to my view using laravel 5.3
if I just use {{ $selectedArticle }} I get the full output :
[{"id":5,"title":"Up up and awayy",
"link":"www.google.be",
"points":0,
"userID":1,
"isDeleted":"FALSE",
"created_at":"2017-01-25 23:53:19",
"updated_at":"2017-01-25 23:53:56"
}]
But when I try using $selectedArticle->id I get the following error:
Undefined property: Illuminate\Support\Collection::$id
How can I call on the properties of the article separatly? (call the id, title,... )
My controller code:
public function index($id)
{
$comments = DB::table('comments')->orderBy('id')->where(['artikelID' => $id, 'isDeleted' => 'FALSE'])->get();
$article = DB::table('articles')->orderBy('id')->where(['id'=> $id])->get();
return view('comments.comments')
->with('storedComments', $comments)
->with('artikelid',$id)
->with('selectedArticle', $article);
}
The variable you're passing to the view is an array and to display the value you should loop through the array like this.
#foreach($selectedArticle as $article)
{{ $article->id }}
#endforeach
Or if you'd like to select only one object using first() function to get the first row, like this:
$article = DB::table('articles')->orderBy('id')->where(['id'=> $id])->first();

Zend Framework: Populating DB data to a Zend Form dropdown element

I have the following form:
<?php
class Application_Form_RegistrationForm extends Zend_Form{
public function init(){
$country = $this->createElement('select', 'country');
$country->setLabel('country: ')
->setRequired(true);
$email = $this->createElement('text', 'email_address');
$email->setLabel('Email Address: ')
->setRequired(true);
$register = $this->createElement('submit', 'register');
$register->setLabel('Create new Account')
->setIgnore(true);
$this->addElements(array(
$country, $email, $register
));
}
}
?>
The list of the countries are present in a table country in a database.
Is there anyway I can populate the country dropdown list with the country names from the database?
Any help is appreciated.
Thanks
You sure can.
In the init method you can set the options with something like this, assuming $db is a Zend_Db adapter:
$options = $db->fetchPairs('SELECT id, name FROM country ORDER BY name ASC');
$country->setMultiOptions($options);
In case you haven't seen the fetchPairs method, it builds an array, where the first column return becomes the key, and the second column the value.
You could do it from controller's action (or even in Service Layer, if to be meticulous), if your list's content depends from some conditions.
Usage:
$form->getElement('country')->addMultiOption('1','USA'); //add single value
$form->getElement('country')->addMultiOptions(array('1'=>'USA', '2'=>'Canada')); //add values by array
$form->getElement('country')->setMultiOptions(array('1'=>'USA', '2'=>'Canada')); //set values by array
Of course, to add values from DB you need to fetch them first.
See http://framework.zend.com/manual/en/zend.form.standardElements.html#zend.form.standardElements.select for more methods available.
The best way is to create a new class for the element:
Put this in "/application/form/element/CountySelect.php"
class Application_Form_Element_CountrySelect extends Zend_Form_Element_Select {
public function init() {
$oCountryTb = new Application_Model_Country();
$this->addMultiOption(0, 'Please select...');
foreach ($oCountry->fetchAll() as $oCountry) {
$this->addMultiOption($oCountry['id'], $oCountry['name']);
}
}
}
And then add it to the form this way:
class Application_Form_RegistrationForm extends Zend_Form{
public function init() {
$this->addElement(new Application_Form_Element_CountrySelect('country_id'));
}
}

Calling function in view of cakephp

I have one team array and want that team name every where to show team name.It is possible to built a global function which can return team name and I call that function from my view means ctp file.
please try this for west:
<?php
// controller name like app,users
// action name like getdata should be in controller
// and you can send parameter also
$output = $this->requestAction('controllerName/actionName/'.$parameter);
?>
There are multiple approaches to this. What I cannot tell from your description is exactly what you are looking for. If it is simply to create an array of items that is accessible in your views, I would put it in app_controller.php
var $teams = array('team1', 'team2', 'team3');
beforeFilter() {
$this->set('teams', $this->teams);
}
Then in your view, you can access the array by the variable: $teams
If you only want to call teams on certain views, it may not be a good idea to set this variable for EVERYTHING. You can get around it by setting up a function in app controller.
function get_teams_array() {
$teams = array('team1', 'team2', 'team3');
return $teams;
}
Then put together an element that will call this function:
views/elements/team.ctp
<?php
$teams = $this->requestAction(
array('controller' => 'app', 'action' => 'teams'),
array('return')
);
/** process team array here as if it were in the view **/
?>
Then you can just call the element from your view:
<?php echo $this->element('team'); ?>
You can add in your /app/config/bootstrap.php file something like:
Configure::write('teams', array('team1', 'team2'));
Then everywhere you can get that array with:
$teams = Configure::read('teams');
and use it.
In CakePHP 3.*, you can use Helpers.
https://book.cakephp.org/3.0/en/views/helpers.html#creating-helpers
1 - Create your helper inside src/View/Helper:
/* src/View/Helper/TeamHelper.php */
namespace App\View\Helper;
use Cake\View\Helper;
class TeamHelper extends Helper
{
public function getName($id)
{
// Logic to return the name of them based on $id
}
}
2 - Once you’ve created your helper, you can load it in your views.
Add the call $this->loadHelper('Team'); inside /src/View/AppView.php:
/* src/View/AppView.php */
class AppView extends View
{
public function initialize()
{
parent::initialize();
$this->loadHelper('Team');
}
}
3 - Once your helper has been loaded, you can use it in your views:
<?= $this->Team->getName($id) ?>

Resources