Passing data in laravel view mail - laravel

im trying to pass more than one variable in my controller to go to the view, but is giving me the error of undifined variable.
I been looking to the documentation and other posts, and still not working.
Controller:
Mail::send('emails.send-references', ['user' => $user,'price'=>$ref->value], function ($m) use ($user) {
$m->from('no-reply#myemal', 'Myname');
$m->to($user->email, $user->name)->subject('My Suject RefMe!');
});
Views mail:
Hello{{$user->name}}blabla:<br>
Ref:{{$refnumber}} <br>
Value: {{$price}}€

You are not sending the $refnumber value to the view:
You can send it like this:
$data = [
'user' => $user,
'price'=>$ref->value,
'refnumber' => 'foo'
];
Mail::send('emails.send-references', $data, function ($m) use ($user) {
$m->from('no-reply#myemal', 'Myname');
$m->to($user->email, $user->name)->subject('My Suject RefMe!');
});
Views mail:
Hello{{$user->name}}blabla:<br>
Ref:{{$refnumber}} <br>
Value: {{$price}}€

Related

Pass Session Data From Controller to View in Laravel 6

I want to create edit user account feature in my Laravel project, so i want to pass current session data from controller to view but i got an error Trying to get property 'name' of non-object. Before passing data, i create login feature to get session, here is my LoginController to get session:
public function loginprocess(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) {
return redirect()->route('index.user');
}
return back()->withInput($request->only('email', 'remember'));
}
Then in another controller i create this function:
public function account()
{
$data=[
'account' => Session::get('user'),
'titleweddinc' => "Account - User Dashboard"
];
return view('user.account',$data);
}
And in the view i use this code:
{{ $account->name }}
In database user i sure I make sure in the user table there is a name field. I try to get {{ $titleweddinc }} and it can appeat. Does anyone know what my mistake is?
use like this
public function account()
{
$data=[
'account' => Session::get('user'),
'titleweddinc' => "Account - User Dashboard"
];
return view('user.account',compact('data'));
}
If Object then print like
{{ $data->account->name}}
Check if Array then print like
{{ $data['account']['name']}}

LARAVEL & VUE: How can I get the API_TOKEN of the logged in user with an API request?

I have a SPA using VUE and LARAVEL 5.8
I have setup an API_TOKEN associated to the logged in user. Everything works fine right after the login. I get the API_TOKEN, I save it into a var and I send it together with the Axios request. In Laravel I have a middleware that is taking care of the token and comparing it with the one setup on the logged in user.
the problem though occur when session expires. Because I still can navigate the private pages and make API requests to save and delete content. This is possible I think because I still have the same API_TOKEN saved in the var and the middleware apparently doesn't get that the session is expired.
So I want to obtain the API_TOKEN every time I'm doing an Ajax, request so when the session expires, I won't get the token and therefore, I won't be able to complete the request.
This is my setup.
web.php is where I have the only php route that points to a singlePageController:
Auth::routes();
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
Then in the singlePageController I return the view:
class SinglePageController extends Controller
{
public function index() {
return view('app', ['loggedUser' => auth()->user()]);
}
}
Then I have the api.php where I have the API routes. As you can see at the end I have the middleware to make it private. Just to make an example this is the one I use for updating the content:
Route::put('event/update/{slug}', 'EventController#update')->middleware('auth:api');
Then the related controller of that API route:
public function update(Request $request, $slug)
{
$event = Event::where('slug', $slug)->first();
$event->title = $request->input('title');
return new EventResource($event);
}
And in the end this is the Resource I use to define what and how the API data is going to be displayed:
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'curator' => $this->curator,
'featured_image' => $this->featured_image,
'body' => $this->body,
'date' => $this->date
];
}
So this above is the flow I have. Then when I do an axios call to update the content, I'm doing something like:
axios({
method: 'PUT',
url: '/api/event/update/' + this.$route.params.slug + '?api_token=' + this.isLogged.apiToken,
data: dataToSave,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
.then((response) => {
this.getNotification('Success: The Event has been saved');
})
.catch((error) => {
this.getNotification('Error: Impossible saving the event');
console.log(error);
})
Do you know how to make it? or if there is a better way to accomplish that?
you and do like, your login method should like this.
public function login(Request $request)
{
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
$user = Auth::user();
$success = $user->createToken(config('app.name'))->accessToken;
return response()->json(["token" => $success, 'status' => 200]);
} else {
return response()->json(['message' => "Email or Password do not match"], 401);
}
}

Laravel routing, redirect with parameters

I'm aware there are similar questions, but the answers provided there do not work for me.
I had the following URL in my Laravel application:
http://example.com/anatomy/18917/why-cant-i-bend-my-back
Now the "anatomy" section has been renamed to "physio" and the new URL for the same content is this:
http://example.com/physio/18917/why-cant-i-bend-my-back
It's a GET route with the format physio/{id}/{slug}
Now, I would like to provide backwards compatibility (for any users that may have bookmarked an article in the old URL format).
So I am trying to redirect, for example, anatomy/18917/why-cant-i-bend-my-back to physio/18917/why-cant-i-bend-my-back. I have tried the following but it's not working:
$router->get('anatomy/{id}/{slug}', function() {
return redirect()->to('physio', ['id' => $id, 'slug' => $slug]);
});
And the error I get is undefined variable: id. If I do the following it redirects correctly to the homepage, but I would rather redirect to the actual article with the given parameters.
$router->get('anatomy/{id}/{slug}', function() {
return redirect()->to('/');
});
change
$router->get('anatomy/{id}/{slug}', function() {
return redirect()->to('physio', ['id' => $id, 'slug' => $slug]);
});
to
$router->get('anatomy/{id}/{slug}', function($id,$slug) {
return redirect()->to('physio', ['id' => $id, 'slug' => $slug]);
});
You nedd to pass $id and $slug in function
source
inside the controller
function($id,$slug) {
return redirect()->to('physio', ['id' => $id, 'slug' => $slug]);
};

Laravel 5, can't insert via request method doesn't exist

That's what i'm trying to do without any success:
In welcome.blade I have a foreach with some boards and subboards(random generated by user) where you can click on subboard and go something like this /subboardOne. I got this on my routes.php
Route::get('/{subboaName}', 'ThreadController#index');
Route::post('/{subboaName}', 'ThreadController#store');
then you can post a thread on this subboard via form but since i really don't know how laravel knows where he is, the form is something like this:
<form class="form col-md-12 center-block" role="form" method="POST" action="/{{$subboardcoll->id}}">
this $subboardcoll->id comes from the controller, where it sends via the index function the collection:
public function index($subboard)
{
$subboardcoll = Subboard::where('subboaName', $subboard)->first();
$threads = Thread::where('subboaId', $subboardcoll->id)
->orderBy('created_at', 'desc')
->get();
return view('threads.thread', compact('threads', 'subboardcoll'));
}
then i'm trying to send my form and store the thread autoinserting the subboardId but laravel doesn't recognize subboards method:
public function store(Request $request)
{
$this->validate($request, [
'comentario' => 'required|max:2000',
//'g-recaptcha-response' => 'required|recaptcha',
//'imagen' => 'required',
]);
$request->subboards()->threads()->create([
'thrName' => $request->nombre,
'thrComment' => $request->comentario,
'thrImg' => $request->imagen,
'thrSubject' => $request->tema,
]);
return redirect()->back();
}
And gives me this erorr:
BadMethodCallException in Macroable.php line 81: Method subboards does not exist.
Can you guys helpme to know why? also is there better form to do what i'm trying? im newbie on laravel, thanks
EDIT:
Thread.php
public function subboard()
{
return $this->belongsTo(Subboard::class, 'subboaId');
}
Subboard.php
public function thread()
{
return $this->hasMany(Thread::class);
}
The method subboards do not exist in a request object. Consider doing this
public function store($id, Request $request)
{
$this->validate($request, [
'comentario' => 'required|max:2000',
//'g-recaptcha-response' => 'required|recaptcha',
//'imagen' => 'required',
]);
Subboard::find($id)->threads()->create([
'thrName' => $request->nombre,
'thrComment' => $request->comentario,
'thrImg' => $request->imagen,
'thrSubject' => $request->tema,
]);
//Alternative query statement
Subboard::where('id', $id)->first()->threads()->create([.....
return redirect()->back();
}

Laravel 4 password reminder: redirection issue

I'm using the Laravel 4 password reminder functionality, as described here: http://four.laravel.com/docs/security#password-reminders-and-reset. In order to generate the token, send the email and create de DB record in the password_reminder table, I use the standard code in my routes file :
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
This code is suppose to send me back to my input form in case of any error (unknown email address for instance). Instead of that, I get a MethodNotAllowedHttpException. The reason is Laravel don't try to send me back to my form URL (which is /password/forgot): he tries to redirect me to /password/remind, in GET, and this route does not exist (of course) in my routes.php file.
I checked the code of the Illuminate\Auth\Reminders\PasswordBroker class, which is responsible of this redirection, and found out this method :
protected function makeErrorRedirect($reason = '')
{
if ($reason != '') $reason = 'reminders.'.$reason;
return $this->redirect->refresh()->with('error', true)->with('reason', $reason);
}
I replaced $this->redirect->refresh() by $this->redirect->back(), and everything is now working as excepted. But as I couldn't find any comment on this bug anywhere, I assume I'm doing something wrong… But I can't find what !
Here is my routes.php file:
Route::get('password/forgot', array('as' => 'forgot', 'uses' => 'SessionsController#forgot'));
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
Route::get('password/reset/{token}', function($token) {
return View::make('sessions.reset')->with('token', $token);
});
Route::post('password/reset/{token}', array('as' => 'reset', 'uses' => 'SessionsController#reset'));
my SessionsController relevant code:
class SessionsController extends BaseController {
[...]
public function forgot() {
return View::make('sessions.forgot');
}
public function reset() {
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'password_confirmation' => Input::get('password_confirmation')
);
Input::flash();
return Password::reset($credentials, function($user, $password) {
$user->password = Hash::make($password);
$user->save();
return Redirect::to('home');
});
}
}
and finally my view code:
{{ Form::open(array('url' => 'password/remind', 'class' => 'form', 'role' => 'form', 'method'=>'post')) }}
<div class="form-group">
{{ Form::label('email', 'E-mail') }}
{{ Form::text('email', '', array('autocomplete'=>'off', 'class' => 'form-control')) }}
</div>
{{ Form::submit("Envoyer", array("class"=>"btn btn-primary")) }}
{{ Form::close() }}
If it is possible, I highly recommend you to upgrade to Laravel 4.1, because it comes with a more flexible (also easier to understand and to work with) solution for password remind/reset.
Check out this example with Laravel 4.1:
https://github.com/laracasts/Laravel-4.1-Password-Resets/blob/master/app/controllers/RemindersController.php

Resources