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();
Related
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
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;
}
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'))
I am very to new to laravel 5.4 and don't know about much about the blade template.
The issue is I am passing the array to the views and trying to get the first index of array element through the provided first() function of blade template but it's giving me error Call to a member function first() on array
Here is my controller code
public function authenticate(Request $request )
{
if (Auth::attempt(['email' => $request->input('email'), 'password' =>
$request->input('password'), 'Status' => 0]))
{
// Authentication passed...
return redirect()->intended('Users');
}
else
{
$json=array('email'=>'You cant leave Email field empty');
return View::make('Auth/login')->with('error',($json));
}
}
Here is my View Code
#if($errors->any())
{{ $errors->first('email') }}
#endif
I am looking for the solution which can exactly suit my needs. If am doing something wrong please correct me.
Thanks...
In your approach you are not using Laravel validations. You just passing an array and basic php arrays does not have methods such as any or first. they belong to Laravel collections.
It is just an array and you can reach array elements as I explained below
so if you wanna keep your code you can do this
#if(isset($error))
{{$error['email'] }}
#endif
But correct way to do is for validation part;
$this->validate($request, [
'email' => 'required| email',
]);
please read documentation deeply about validations and authentication https://laravel.com/docs/5.4/validation
You may use
#foreach ($errors as $error)
{{ $error }}
#endforeach
So you can see the list of the error returned
I am trying to retrieve data from another controller to display it in the PagesController's view using an element. I have a table
service_categories(id, service_category);
my ServiceCategoriesController looks like this
public function category() {
$serviceCategories = $this->paginate();
if ($this->request->is('requested')) {
return $servicesCategories;
} else {
$this->set('serviceCategories', $servicesCategories);
}
}
my category.ctp element looks like this
<?php
$serviceCategories = $this->set('serviceCategories/category');
foreach ($serviceCategories as $serviceCategory):
echo $serviceCategory['ServiceCategory']['service_category'];
endforeach;
But I seem to get an undefined value of "$serviceCategories" when I create an alert before the foreach loop. Please assist! What am I missing?
I rewrite the answer after turning on brain:
In your element replace:
$serviceCategories = $this->set('serviceCategories/category');
with
$serviceCategories = $this->requestAction('service_categories/category');