Laravel undefined variable in view - php

I'm new to laravel. Using version 5.3 and tried to search but don't see what I'm doing wrong. I keep getting an "Undefined variable: user" in my view. I'm also doing form model binding. Model binding works properly when manually entering URL. Just can't click on link to bring up edit view.
My routes:
Route::get('/profile/edit/{id}', 'ProfileController#getEdit');
Route::post('/profile/edit/{id}', 'ProfileController#postEdit');
My controller:
public function getEdit($id){
$user= User::findOrFail($id);
return view('profile.edit', compact('user'));
}
My view:
<li>Update profile</li>
My form:
{!! Form::model($user,['method' => 'POST', 'action'=> ['ProfileController#postEdit', $user->id]]) !!}

public function getEdit($id){
$user= User::findOrFail($id);
return view('profile.edit', ['user' => $user]);
}
public function postEdit($id){
$user= User::findOrFail($id);
return view('profile.edit', ['user' => $user]);
}

Try this for pass data array in view
public function getEdit($id){
$data['user'] = User::findOrFail($id);
return view('profile.edit')->withdata($data);
}
in view page try to print $data
{{ print_r($data) }}

Please edit your getEdit method
public function getEdit($id){
$user= User::findOrFail($id);
dd($user);
return view('profile.edit', compact('user'));
}
check if there is any data user variable.

In my opinion, the statement in your view
<li>Update profile</li>
is causing the issue. You may confirm this by looking at the URL in the address bar after clicking on the Update profile link.
Try changing it to this
<li>Update profile</li>

Related

Undefined variable $user->username (Laravel 5.7)

I can't get the data from the database. Getting an error:
ErrorException (E_ERROR)
Undefined variable: user
(View:/Users/alex/Desktop/sites/tj/resources/views/user/submissions.blade.php)
Controller:
public function __construct()
{
$this->middleware('auth', ['except' => ['getById',
'getByUsername', 'submissions', 'comments', 'showSubmissions',
'showComments']]);
}
and
public function showSubmissions($username)
{
$user = new UserResource(
User::withTrashed()->where('username', $username)->firstOrFail(),
true
);
$submissions = SubmissionResource::collection(
Submission::whereUserId($user->id)
->withTrashed()
->orderBy('created_at', 'desc')
->simplePaginate(15)
);
return view('user.submissions', compact('user', 'submissions'));
}
View:
{{ $user->username }}
API:
Route::get('/user', 'UserController#getByUsername');
I need get information about user (username).
What is the problem and where is the error?
Based on your comment you have this route:
Route::get('/submission', function () {
return view('user.submissions');
});
When you are loading this view, you are not passing the user object to it. Then when the view is running, it is trying to access a variable that does not exist.
To fix this, you need to pass a variable to the view you are loading. For example, you could do something like this:
Route::get('/submission', function () {
return view('user.submissions', ['user' => auth()->user()]);
});
Note that you can change how you get the user instance depending on your use case. I am just getting the authenticated user to demonstrate the principle.

How to select an id in route pass it into the controller and fetch data against that id and redirect it view again in laravel 5.6

How to pass id from veiw into controller in then into another view again??
First of all this a basic question you should be able to search it anywhere on the internet. any how below is the solution.
web/routes.php:
Route::get('user/{id}','USerController#find')->name('user.get');
Or by passing user object in the route:
Route::get('user/{user}','USerController#find')->name('user.get');
UserController:
the below function accepts user object as a parameter in the route we defined above.
public function find(user $user)
{
return view('user.detail',compact('user'))
}
or
public function find($id)
{
$user = USer::find($id);
return view('user.detail',compact('user'))
}
resources/view/user/detail.blade.php:
{{ $user -> name }}
{{ $user -> email }}
and in order visit the route user.find use the below line:
View Detail
No you can use this code as reference to your project.
first solution is .
change route
Route::get('/show_vedio/{$id}', 'VedioController#show')->name(show_videos);
and use this {{ route('show_vedios', $vedio->id )}} in href
it's not entirely clear what you are trying to do, maybe i will help you:
public function show(int $id): View
{
$video = Video::find($id);
return view('video.show', ['video' => $video]);
}

How to set URL so it loads the user page

In route.php I have the following...
Route::get('/user/{username}', array(
'as' => 'profile-user',
'uses' => 'ProfileController#user'
));
In ProfileController I have the following...
class ProfileController extends BaseController {
public function user($username) {
$user = User::where('username', '=', $username);
if($user->count()) { // if the corresponding user exists...
$user = $user->first();
return View::make('profile.user')
->with('user', $user);
}
return App::abort(404);
}
}
In navigation.blade.php I have the following...
<li>User Profile</li>
How can I make it so that navigation.blade.php will provide the correct link to the user profile? At the moment the link looks like the following in html...
http://website.dev/user/%7Busername%7D
I'd like it to look like this:
http://website.dev/user/currentlyLoggedInUserName
You can try using HTML::link. Example:
{{ HTML::link('/user/<?=$user_name?>', 'User Profile')}}
You should use
<li>User Profile</li>
because it is a Laravel PHP function url() that must resolve first, and the result is passed to Handlebars.
This is how I solved it. I'll leave the answer here for other people.
<li>User Profile</li>

Laravel Error : ErrorException Missing argument 1?

I am using Laravel 4 and I am getting ERROR: when I visit admin/profile/: Missing argument 1 for AdminController::getProfile()
My AdminController code :
public function getProfile($id) {
if(is_null($id)) Redirect::to('admin/dashboard');
$user = User::find($id);
$this->layout->content = View::make('admin.profile', array('user' => $user));
}
My routes.php :
Route::controller('admin', 'AdminController');
My admin/profile (blade) view :
#if(!is_null($user->id))
{{ $user->id }}
#endif
How could I fix this? I want when they go to admin/profile without ($id) to redirect to dashboard.
You told Laravel that your getProfile method has one parameter:
public function getProfile($id) {
}
If you want to a request to succeed, you have to pass it in your URL:
http://appdev.local/admin/profile/1
If you want to see it fail (redirect to dashboard), you'll have to add a default value to your function argument:
public function getProfile($id = null) { ... }
But you better add this value to it anyway, since you can have bots (or even people) trying to access that route without the parameter.
Your view is too generic too, you have to check if your $user is set:
#if(isset($user) && !is_null($user->id))
{{ $user->id }}
#endif
As noted in the comments, the line
if(is_null($id)) Redirect::to('admin/dashboard');
Must have a return:
if(is_null($id)) return Redirect::to('admin/dashboard');
About sharing the user to your layout, the problem is that your getProfile($id) is already passing a $user to your view, so what you could do is to add this to your __construct():
if (Auth::check())
{
$user = Auth::getUser();
View::share('loggedUser', $user);
}
And in your view:
#if(isset($user) && !is_null($user->id))
{{ $user->id }}
#else
{{ $loggedUser->id }}
#endif
About the user not found problem, you have many options, this is one:
public function getProfile($id) {
if (is_null($id))
{
return Redirect::to('admin/dashboard');
}
if ($user = User::find($id))
{
$this->layout->content = View::make('admin.profile', array('user' => $user));
}
else
{
return Redirect::to('admin/dashboard')->withMessage('User not found');
}
Try setting a default null value to $id like this :
public function getProfile($id = null) {
...
}

Laravel 4: undefined variable error when submitting data from the view

I'm trying building a timer app - this form should submit the time (which it does) AND the client name as populated from the database, it looks like this:
{{ Form::open(array('action' => 'TasksController#store', 'name' => 'timer')) }}
{{ Form::select('client', $client , Input::old('client')) }}
{{ Form::hidden('duration', '', array('id' => 'val', 'name' => 'duration')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
My controller that generates this page looks like this:
public function index()
{
$client = DB::table('clients')->orderBy('name', 'asc')->lists('name','id');
return View::make('tasks.index', compact('task', 'client'));
}
I am getting a "Undefined variable: client" when I submit the form. I can't see why.
What am I doing wrong?
EDIT: the store function in my TasksController looks like this:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Task::$rules);
if($v->passes())
{
$this->task->create($input);
return View::make('tasks.index');
}
return View::make('tasks.index')
->withInput()
->withErrors($v)
->with('message', 'There were validation errors.');
}
You are returning the View::make() from your store() function, which is not the 'resourceful' way of doing it.
Your view is expecting to have $client included in it - but because store() does not return a $client - the error is generated.
Assuming you are using a resourceful controller - your store function should look like this:
public function store()
{
$input = Input::all();
$v = Validator::make($input, Task::$rules);
if($v->passes())
{
$this->task->create($input);
return Redirect::route('tasks.index'); // Let the index() function handle the view generation
}
return Redirect::back() // Return back to where you came from and let that method handle the view generation
->withInput()
->withErrors($v)
->with('message', 'There were validation errors.');
}

Categories