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
Related
I m new in Laravel 8. Please give any suggestion for the given below code or answer my question:
Given below is my code an example of what i really want to get:
my data is :
[{"column_1_1":"value_1_1","column_1_2":"value_1_2"},{"column_2_1":"value_2_1","column_2_2":"value_2_2"}]
and I want
Array
(
[0] => stdClass Object
(
[column_1_1] => value_1_1
[column_1_2] => value_1_2
)
[1] => stdClass Object
(
[column_2_1] => value_2_1
[column_2_2] => value_2_2
)
)
I am adding this answer as the other is showing only one way and is the least used... Mine is the Laravel way, the one you should always use and the most you are going to see all the time...
If you have a Model who's property is, for example, data, you don't have to overwrite how it is read by doing getDataAttribute and use json_decode...
If that property/field is a JSON/TEXT in your database (hence storing JSON), you just have to cast it.
class YourModel extends Model
{
protected $casts = [
'data' => 'array'
];
}
So later you can do:
foreach ($model->data as $item) {
...
}
And store info in it like:
$array = ['products' => ['item1', 'item2'], 'quantity' => 2];
$model->data = $array;
And it will get saved on the database like {products: ["item1", "item2"], quantity: 2}
Bro you just need to add the accessor method in your model like:
Guess you have xyz column in your database
public function getXyzAttribute($xyz)
{
return json_decode($xyz);
}
It will directly return the array.
Hope it worked. :)
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
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'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();
I would like to send an array as an argument in a twig command like:
{{ render(controller("AppBundle:Default:Test"), { 'myarray': array }) }}
But I'm not able to figure out the good way. Let's explain the following simple example with the basic AppBundle. In my project, the render will ask for a render from another Bundle. I'm sure the process is the same, whenever it's the same Bundle or not.
In the default Controller, I put this:
/**
* #Route("/test", name="test")
*/
public function testAction()
{
return $this->render('AppBundle:Default:Test.html.twig', array (
'tests' => array("Test 1", "Test 2", "Test 3", "Test 4")
));
}
/**
* #Route("/test2", name="test2")
*/
public function test2Action($tests = array())
{
var_dump($tests);
return $this->render('AppBundle:Default:Test2.html.twig', array(
'tests' => $tests
));
}
I added a var_dump to track the array, and it is not forwarded to the test2Action function.
In the Test.html.twig, I have this code:
{{ render(controller("AppBundle:Default:Test2"), { 'tests': tests }) }}
In the Test2.html.twig, I have this code:
{% for test in tests %}
{{ test }}</br>
{% endfor %}
Finally, I have this in the navigator:
array(0) { }
Nothing about the array I sent to the test2Action function through the render/controller function in twig.
I'm using Symphony 3.0.3, but even in Symphony 2.8, I cannot find any relevant information.
Maybe I'm not using the best way to do this.
Please, could you help me. I really need to send an array from a bundle to another, in order to have both independent from the other.
Thank you so much,
Stef.
Seems a bracket mistake. In the Test.html.twig, try this:
{{ render(controller("AppBundle:Default:Test2", { 'tests': tests }) ) }}
instead of:
{{ render(controller("AppBundle:Default:Test2"), { 'tests': tests }) }}
Hope this help