how do I get the updated_at and created_at - laravel

I'm making my first Larevel (4) application and I want to display the date that it was created and I'm getting this problem: Unexpected data found. Unexpected data found. Unexpected data found. Data missing
when I try to do this in my blade template
#extends('layout')
#section('content')
<h3>Name: {{ $user->name }}</h3>
<p>Email: {{ $user->email }}</p>
<p>Bio: {{ $user->bio }}</p>
#endsection()
#section('sidebar')
<p><small>{{ $user->created_at }}</small></p>
#endsection()
#stop
and my controller
<?php
class UserController extends BaseController
{
public $restfull = true;
public function get_index() {
//$users = User::all();// gets them in the order of the database
$users = User::orderBy("name")->get(); // gets alphabetic by name
$v = View::make('users');
$v->users = $users;
$v->title = "list of users";
return $v;
}
public function get_view($id) {
$user = User::find($id);
$v = View::make('user');
$v->user = $user;
$v->title = "Viewing " . $user->name;
return $v;
}
}
?>
it works as soon as I take out :
<p><small>{{ $user->created_at }}</small></p>"
any ideas how to access those values, I checked and they DO exist in my table.
this is the schema of my table
CREATE TABLE "users" ("id" integer null primary key autoincrement, "email" varchar null, "name" varchar null, "bio" varchar null, "created_at" datetime null, "updated_at" datetime null);

So here's what I did to fix it.
in the migrations I did this:
class CreateTable extends Migration {
public function up()
{
Schema::create('users', function($table) {
$table->string('name');
$table->timestamps();
});
}
/* also need function down()*/
I had the insertions like this in my migrations to add some users.
class AddRows extends Migration {
/* BAD: this does NOT! update the timestamps */
public function up()
{
DB::table('users')->insert( array('name' => 'Person') );
}
/* GOOD: this auto updates the timestamps */
public function up()
{
$user = new User;
$user->name = "Jhon Doe";
$user->save();
}
}
Now when you try to use {{ $user->updated_at }} or {{ $user->created_at }} it will work! (assuming that you passed $user to the view)

There are a few things going on here that should probably be fixed. Since this is a restful controller, Laravel expects your function names to be camelCase rather than snake_case.
The way you are passing variables to the view also is not looking right. Try passing the $users variable to the view with return View::make('users')->with('users',$users);.
Another thing is you are passing a collection of users to the view, which means you won't just be able to echo user information. To get the user information out of the collection, you must iterate through the collection with a loop. (Your app will probably break again once you get more than one user in)
foreach($users as $user)
{
echo $user->name;
echo $user->email;
echo $user->bio;
}
Because the way you have your sidebar and content sections showing user information, what you probably actually want to do to get your user is something along the lines of $user = User::find(Auth::user()->id); meaning it would be returning one user and you'd be able to lose the loop.
One more thing I just seen. If you are setting up a restful controller, the proper property is public $restful = true; though I'm not sure that's actually being used anymore because you are basically setting that in routes.php with Route::controller('user', 'UserController');.

Related

Trying to get property 'post_titile' of non-object

This is My Controller.
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
//dd($page);
return view('web_views.index',['page' => $page]);
}
This is my view page
<h4>{{$page->post_titile}}</h4>
It's better to use Route-Model Binding I think.
Your route (if you are using resource route, it's already done):
Route::get('posts/{post}', 'PostController#show); // domain.tld/posts/1
Your method should look like this:
public function show(Post $post)
{
return view('web_views.index',compact('post'));
}
In your view:
<h4>{{ $post->post_titile }}</h4>
May be $posts->id you are passing, has no result in database so you need to check it by using if-statement
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
if($page == null){
$page = ['post_title' => 'Not Available'];
}
return view('web_views.index',['page' => $page]);
}
I believe this error is because of not finding data for an ID into database. So if as per above script will pass the fetched data to view otherwise it will push an item into $page array.

Laravel: Access collection in view

I would like to display users that have sent or got message/s.
User Model:
public function messages_sender()
{
return $this->hasMany('App\Message', 'sender_id');
}
public function messages_recipient()
{
return $this->hasMany('App\Message', 'recipient_id');
}
MessageController
public function index()
{
$users = User::with('messages_recipient', 'messages_sender')->paginate(5);
//return $users;
return view('message.index',compact('users'));
}
Messages View:
{{ $user->messages_recipient['recipient_id'] }}
Result is an error in view "Undefined index: recipient_id" or when i try to access any of them (sender_id, recipient_id). I understand that not all users have messages, as i see in JSON format, so i used:
#if($user->messages_recipient->has('recipient_id'))
{{ $user->messages_recipient['recipient_id'] }}
#endif
and than error did not show.
JSON: https://pastebin.com/NFSWMp7r
As I am new to Laravel i could use some help. In similar example it worked when I needed to get users and name of their role (admin, user).
You can access the Users form the App\Message Model instead of the other way round.
Message Model:
public function senders()
{
return $this->belongsTo('App\Users', 'sender_id');
}
Message Controller
public function index()
{
$senders = Message::senders()->paginate(5);
return view('message.index',compact('senders'));
}
Dont blame me but I am not sure, if the sender_id is just right there :-P
Unfortunately, if you want unique records this will not work.
Your using the message_recipient as an array and if a key doesn't exist on an array PHP will always throw an error. The hasMany relationship returns a Collection of Message objects so you would need to use it as an object with:
#foreach($user->messages_sender as $message)
{{ $message->id }}
#endforeach
and
#foreach($user->messages_recipient as $message)
{{ $message->id }}
#endforeach
or if you just wanted all of the message ids you could do $user->messsages_recipient->pluck('id') and that would return all of the ids of the Message objects.

Laravel5.6 "Call to a member function delete() on null " , delete a row in table

I want to delete a row from table. The function I used in controller is:
public function destroy($id) {
$category = Category::find($id);
$category->delete();
return redirect()->back();
}
However it throws me an error:
Call to a member function delete() on null
When I use this code:
public function destroy($id) {
$category = Category::find($id);
dd($id);
}
It is showing the correct id i.e.
"1"
And when I use
public function destroy($id) {
$category = Category::find($id);
dd($category); // or
dd(Category::find($id);
}
I get the output
null
on the screen.
As mentioned in comments, the error you're getting is probably due to no category exists in the database for the given ID.
Then, when you try to find the category for that ID:
$category = Category::find($id);
The value of $category variable is null. Therefore, you get an error for trying to call delete() method on null. Under the hood, it would be the same as doing the following:
null->delete();
Which, doesn't work.
You could check the value of $category before trying to delete it. Or you may use a query to delete all records matching a given condition, in your case id = $id. This way:
public function destroy($id)
{
Category::where('id', $id)->delete();
return redirect('/')->back();
}
Refer to Deleting Models By Query in the Eloquent docs for details on how that works.
What worked for me is the following (I ensured that the $id was passing from the view):
public function destroy($id)
{
$vendor = Vendor::findorFail($id);
$vendor->delete():
}
for some reason when I did the following it showed null
public function destroy($id)
{
$vendor = Vendor::find($id);
$vendor->delete():
}
This is the view part:
{!! Form::open(array(
'style' => 'display: inline-block;',
'method' => 'DELETE',
'onsubmit' => "return confirm('".trans("global.app_are_you_sure")."');",
'route' => ['vendor.destroy', $vendor->vendor_id])) !!}
{!! Form::submit(trans('global.app_delete'), array('class' => 'btn btn-xs btn-danger')) !!}
{!! Form::close() !!}

Laravel passing data to page

I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}

Laravel form select poulated by eloquent model

I am currently making an edit page for some data in my database, and on the edit page I am trying to make a Form::select which lists the people in my users table.
controller-which-makes-the-edit-view.php
<?php
class AdminController extends BaseController
{
public $restful = true;
public function getUpdatePage($id)
{
return View::make('data_edit')
->with('title', 'Rediger måling/oppgave')
->with('data', Routine::find($id))
->with('emp', Emp::lists('user_name', 'id'));
}
data_edit.blade.php
{{ Form::label('emp', 'Ansatt') }}
{{ Form::select('emp', $emp, $data->emps->user_name) }}
Now my question is how would I go about making the default value for the select the person that saved the row which is currently being edited?
I do apologize if this already is answered, I couldn't seem to find it (neither here nor google).
This is Form::select() definition:
public function select($name, $list = array(), $selected = null, $options = array())
{
}
The third parameter is the item to be selected. You are currently passing
$data->emps->user_name
To it, but it depends on the data you have on $emp, because you must pass to it the array key, not the value.
Note that for now (Laravel 5.3+), ::lists is obsolete, use ::pluck instead.

Resources