Can't get data from Auth::user() - laravel

I am new to Laravel.
I am using external API into login page
So I use this into login controller
note : $userId, $nama are data I get from external API, and I want it to store in Auth.
$user = [
'id' => $userId,
'nama' => $nama,
'prodi' => $prodi,
'email' => $email,
'nidn' => $nidn,
'nip' => $nip,
'jabatanFungsional' => $jabatanFungsional,
'keaktifan' => $keaktifanDosen
];
$user = new AuthUser($user);
Auth::login($user);
return view('pages.biodata');
in view biodata, I use this code and that works
{{ auth()->user()->nama }}
but when I go to another view where code
{{ auth()->user()->nama }}
is still using, I got error:
Attempt to read property "nama" on null
even though I still don't use syntax Auth::logout()
Can some one tell me what is wrong?
I want to login using external API, and get data from that so I can pass that data to my view using Auth::user()->somedata.
For first return view from controller, I can do Auth::user()->nama and display a text, but when I go to another view and using Auth::user()->nama, an error Attempt to read property "nama" on null displays.

Related

Add the inserted id to the pivot table

I have a users, items, user_item tables. I need to populate the user_item table with a user_id and item_id when a user is created.
so far, I have a basic registration function
public function register(Request $request) {
$user = User::create([
'name' => $request->name,
'user_type' => $request->user_type,
'email' => $request->email,
'password' => bcrypt($request->password)
]);
$token = auth()->login($user);
return $this->respondWithToken($token);
}
So far it saves only to the users table ofcourse.
I've looked at some documentations on using attach(), however, I got stuck on this one..
In the register function, i added a $item array:
$item = Item::create([
'user_id' => !!!!, -> How do I get the id of the inserted user
'instrument_id' => $request->instrument_id
]);
$user->role()->attach($item)
Also, what is role()? is it a built-in laravel function?
Note that I haven't tried running this function since I got stuck on these problems. So I don't event know if it's gonna work.
Anyone help me on this one? I'm a laravel newbie and got really confused on the documentations.
the method create return the model it self after loading it's attributes from db,
so when you want the user id just use $user->id after create() method.
for the default permission that shipped with laravel it is
spatie/laravel-permission
and to assign role to a user you can use:
$user->assignRole('writer'); // just set role name

Redirect response data to another view

im trying in my controller method to pass some data to a order sucess page, information regarding the details of payment, but i cant make it work or pass the data.
In my case i wish for example pass this request
$http = new \GuzzleHttp\Client;
$response = $http->request('POST', 'https://domain', [
'form_params' => [
'chave' => 'somekey',
'valor' => Cart::total(),
'id' => $order->id,
]
]);
$result = json_decode((string) $response->getBody(),true);
Cart::destroy();
return redirect()->route('frontend-cart-success')->with( ['data' => $result] );
And then in my view sucess page just calling the $data Info to show on my blade file.
But i cant it ut it work.
My route to pass in sucess page:
Route::get('cart/success/', 'Frontend\CartController#showSuccess')->name('frontend-cart-success');
Best regards
I code mostly in SPAs, but according to the API (https://github.com/laravel/framework/blob/5.7/src/Illuminate/Http/RedirectResponse.php#L42), it's flashing that data to the session, so you're going to have to get the data back out using the session.
See: https://laracasts.com/discuss/channels/laravel/redirect-to-route-with-data?page=1

Why laravel view data persists during testing?

I have encountered an awkward bug. I have the following code:
// if user clicked 'register with Facebook' button
if(session()->has('providerUser')){
$name = explode(' ', session('providerUser')->getName());
view()->share([
'first_name' => $name[0],
'last_name' => $name[1] ?: '',
'email' => session('providerUser')->getEmail()
]);
}
I have another method that clears the session, so when I get redirected back the view does not have variables $first_name, $last_name, $email.
But when I do the same checks in the session - they are present. What is strange - that {{session()->has('providerUser')}} is empty in the view and I have also debugged the controller it does not get inside the if(){} statement. And I am sure I am not declaring those variables anywhere else.

Update / post database colum in Laravel

I have a general question.
I have a search form in larvel which returns results form the database.
in these i have an input field to enter a price if price is == 0
what my problem is when i enter price and submit it returns to the search page without my previous search results i.e it doesn't refresh the same page with results and the newly updated field etc.
form in view
{{ Form::open(['action' => 'price_input'])->with($gyms) }}
{{ Form::text('enter_price', null, ['class' => 'form-control', 'size' => '50', 'id' => 'enter_price', 'autocomplete' => 'on', 'runat' => 'server', 'required' => 'required', 'placeholder' => 'enter price!', 'style' => 'margin-bottom: 0px!important;']) }}
{{ Form::submit('Search', ['class' => 'btn btn- primary', 'style' => 'margin-left: 10px;']) }}
{{ Form::close() }}
route
Route::post('/', [ //not used yet
'as' => 'price_input',
'uses' => 'PagesController#priceUpdate'
]);
Model
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
return Redirect::back()->withInput();
}
Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gym);
}
not bothering with model as that works fine.
any ideas guys?
Thanks for your answer,
i have changed my controller to this
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
but when i run it i get
Missing argument 1 for PagesController::priceUpdate()
with the $gyms being passed into the method.
if i take out the $gyms that goes away but not sure if its still being passed with session or not, sorry im a novice.
orignally i had a search box which when run returns
return View::make('pages.home')->with($data);
what is the difference between that and
return View::make('pages.home')->with($data);
when i do the above line it returns to the search page with no search options from before update the form, any ideas?
Currently, you are just retrieving an existing session and doing nothing with it. You need to do:
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
Or
return Redirect::to('pages.home')->with('gyms', Session::get('gyms'));
Then you can access the gyms in the view with $gyms.
Alternatively, you could access Session::get('gyms') in the view as well.
Also, not sure if it's just the way you pasted it here, but you have an unnecessary space before the ->with. Just wanted to make sure that's not part of the issue, too!

Get the model ID when updating a resource

I have a form that will submit a Patch request to the controller's update method.
But the update method requires to have $id, as you can see below whenever I try that I get a
No query results for model [Item]. Since the update method did not receive the $id of the model
public function update($id)
{
$item = Item::findOrFail($id);
$update = Input::all();
// some codes to save changes
return Redirect::route('items.index');
}
Another thing is that whenever I submit the form, url turns into something like this:
mw.dev/items/%7Bitems%7D
Edit
routes.php
Route::resource('items','ItemsController');
ItemController
public function edit($id)
{
$item = Item::findOrFail($id);
return View::make('items.edit')->with('item',$item);
}
I have included the code on my edit.blade.php
{{Form::open(array('route' => 'items.update', 'method'=>'patch'))}}
{{Form::text('barcode', $item->barcode, array('placeholder' => 'barcode'))}}
{{Form::text('imei',$item->imei, array('placeholder' => 'imei'))}}
{{Form::text('item_name', $item->item_name, array('placeholder' => 'item name'))}}
{{Form::submit('edit')}}
{{Form::close()}}
You have to pass the model to your view and need to pass the id parameter when generating the form. Assume that you have a User model and it's available in the view. So you may generate the form action using something like this:
// Using Form::open method with route
Form::open(array('route' => array('route.name', $user->id)))
// Using Form::model method with route
Form::model($user, array('route' => array('route.name', $user->id), 'method' => 'patch'))
// Using Form::open method with action
Form::open(array('action' => array('Controller#update', $user->id), 'method' => 'patch'))
// Using Form::open method with url
Form::open(array('url' => 'something/update/' . $user->id, 'method' => 'patch'))
Check more on Opening A Form.
The URL
mw.dev/items/%7Bitems%7D
is most likely the url-encoded form of
mw.dev/items/{items}
I suppose there is a problem in the form submission or in the <form>'s action paremeter or in the Route::* declaration in routes.php.
This could also explain why you don't get any $id upon submission.

Resources