Cant't edit or delete post in laravel project - laravel

Hello dear i have an problem when user need too delete or edit post , laravel show error " you can't edit post ... " i use a model and controller in laravel and user "auth" system id for access post for delete or edit now see my work :
Index View
#extends('layouts.app')
#section('content')
#auth
<h6 class="alert alert-dark">Dear Guest {{ Auth::user()->name }} for send a post <a class="btn btn-success" href="{{ route('ads.create') }}">Click</a> Here</h6>
#endauth
#guest
<div class="alert alert-primary">for send a post you can <a class="btn btn-success" href="{{ route('register') }}">Register</a></div>
#endguest
#if(count($adses) > 0)
<div class="row">
#foreach($adses as $ads)
<div class="col-xl-3 col-lg-3 col-md-6 col-sm-12">
<div class="card mb-4">
<img class="card-img-top img-fluid" src="/storage/cover_images/{{$ads->cover_image}}" alt="Card image cap">
<div class="card-body">
<h6 class="card-title">{{ $ads->title }}</h6>
#if(!Auth::guest())
#if(Auth::user()->id == $ads->user_id)
<div class="row">
{!!Form::open(['action' => ['AdsController#destroy', $ads->id], 'method' => 'POST',]) !!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close() !!}
Edit
</div>
#endif
#endif
</div>
</div>
</div>
#endforeach
{{ $adses->links() }}
#else
<p class="alert alert-warning" role="alert">any post !</p>
</div>
#endif
#endsection
Ads Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ads extends Model
{
protected $table = 'ads';
public $primaryKey = 'id';
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
}
User model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function adses(){
return $this->hasMany('App\Ads');
}
}
Ads Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Ads;
class AdsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$adses = Ads::orderBy('created_at', 'desc')->paginate(16);
return view('ads.index')->with('adses', $adses);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('ads.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'image|nullable|max:1999',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$ads = new Ads();
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
$ads->user_id = auth()->user()->id;
$ads->cover_image = $fileNameToStore;
$ads->save();
return redirect('/home')->with('success', 'آگهی شما با موفقیت درج شد .');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$ads = Ads::find($id);
return view('ads.show')->with('ads', $ads);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant edit other user's post');
}
return view('ads.edit')->with('ads', $ads);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Ads $ads
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required',
'adsType' => 'required',
'cover_image' => 'required',
]);
// Handle File Upload
if($request->hasFile('cover_image')){
// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
}
$ads = Ads::find($id);
$ads->title = $request->input('title');
$ads->body = $request->input('body');
$ads->adsType = $request->input('adsType');
if($request->hasFile('cover_image')){
$ads->cover_image = $fileNameToStore;}
$ads->save();
return redirect('/')->with('success', 'your post is update');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$ads = Ads::find($id);
if(auth()->user()->id !== $ads->user_id){
return redirect('/')->with('error', 'you cant delete other user's post');
}
if($ads->cover_image != 'noimage.jpg'){
// Delete Image
Storage::delete('public/cover_images/'.$ads->cover_image);
}
$ads->delete();
return redirect('/')->with('success', 'Post Removed');
}
}
Routs
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('/', 'AdsController');
Route::resource('ads', 'AdsController');
now , after send a post and login in system user cant delete or edit her post .
Thank you

auth()->user()->id !== $ads->user_id .
Уou have this line. And if user not login when he creating post, you are will be have user_id == null. Check in DB than user_id?

I solved my problem
if(auth()->user()->id !== $ads->user_id)
Since you're using !==, make sure your user_id is integer

Related

Laravel cant seem to implement search properley

blade.php file that shows all Posts from my database
Im trying to add a search bar that will filter all these posts to prioritise according to title but i cant seem to get it working at all
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-12 pt-2">
<div class="row">
<div class="col-8">
#if (Auth::user() && Auth::user()->is_admin)
<h1 class="display-one">Bloggy</h1><h2>Admin</h2>
#endif
</div>
<!-- Check to see if the user is a guest, if they are the Add post button is hidden -->
#if(!Auth::guest())
<div class="col-4">
Add Post
</div>
#endif
</div>
#if (Auth::user() && Auth::user()->is_admin)
<div class="col-4">
Manage Users
</div>
#endif
<!-- HERE -->
<form>
<input type="search" class="form-control" placeholder="Find user here" name="search">
</form>
#forelse($posts as $post)
<ul>
<li>{{ ucfirst($post->title) }}</li>
<li>{{ ucfirst($post->created_at) }}</li>
</ul>
<p>
{{ $post->user->name }}
</p>
<p>
{{ $post->tag->name }}
</p>
#empty
<p class="text-warning">No blog Posts available</p>
#endforelse
</div>
</div>
</div>
#endsection
Here is my posts controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('created_at', 'desc')
->paginate(20);
return view('posts/index', [
'posts'=> $posts
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts/create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
// References
// Jefferey Way. laracasts. Laravel 8 from scratch. laracasts.com. https://laracasts.com/series/laravel-8-from-scratch
public function store(Request $request)
{
$request->validate([
'tag_id' => 'required',
'title'=> 'required',
'body'=> 'required',
]);
$post = new Post;
//dd(Auth::user());
$post->user()->associate(Auth::user());
$post->title = $request->title;
$post->body = $request->body;
$post->tag_id = $request->tag_id;
$post->save();
return redirect()->route('posts.index')
->with('success', 'Post created succesfully');
}
/**
* Display the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function show(Post $post)
{
return view('posts.show', [
'post'=> $post,
]);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
return view('posts.edit', [
'post' => $post
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
$request->validate([
'title' => 'required',
'body' => 'required'
]);
$post->update($request->all());
return redirect()->route('posts.index')
->with('success', 'Post updated succesfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
$post->delete();
return redirect()->route('posts.index')
->with('success', 'Deleted Succesfully');
}
public function showPostsByUser(User $user)
{
$posts = Post::where('user_id', $user->id)->get();
return view('posts.userposts', compact('posts', 'user'));
}
// Search function here
public function search()
{
// Check for search input
if (request('search')) {
$posts = Post::where('title', 'like', '%' . request('search') . '%')->get();
} else {
$posts = Post::all();
}
return view('posts.show')->with('posts', $posts);
}
}
Here is my routes file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\WelcomeController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\CommentController;
use App\Http\Controllers\RegisterController;
use App\Http\Controllers\AdminController;
use App\Models\Tag;
use App\Model\Post;
use App\Model\Users;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [WelcomeController::class, 'index']);
Route::resource('/posts', PostController::class);
Route::get('/posts/search', [PostController::class, 'search'])->name('search');
Route::post('posts/{post}/comments', [CommentController::class, 'store']);
Route::get('/register', [RegisterController::class, 'create'])->name('register.create')->middleware('guest');
Route::post('/register', [RegisterController::class, 'store'])->name('register.store')->middleware('guest');
Route::get('/login', [LoginController::class, 'login'])->name('login');
Route::get('/logout', [LoginController::class, 'logout'])->name('logout');
Route::post('/login', [LoginController::class, 'authenticate'])->name('authenticate');
Route::resource('/admin', AdminController::class)->middleware('admin');
// Route::get('/tags/{tag}', function(Tag $tag) {
// return view('posts/index', [
// 'posts'=>$tag->posts
// ]);
// });
Route::get('/posts/user/{user}', [PostController::class, 'showPostsByUser'])->name('posts.showPostsByUser');
I cant seem to get anything working when i search in the bar on the main page my url changes to
http://localhost/posts?search=postname
And then nothing happens
Any help would be appreciated thanks, still trying to learn Laravel
EDIT:
It just seems to stay on the same page just the url changes
So you have a couple options here. You can define a separate route for /posts/search, or you can hook into the existing /posts (index) Route:
Define a GET Route for this new Search URL:
routes/web.php:
Route::get('/posts/search', [PostController::class, 'search'])->name('search');
PostsController.php:
public function search(Request $request) {
$postsQuery = Post::latest(); // `latest()` is shorthand for `orderBy('created_at', 'DESC');`
if ($request->has('search')) {
$postsQuery = $postQuery->where('title', 'like', '%' . $request->input('search') . '%');
}
$posts = $postQuery->paginate(20);
return view('posts.index', ['posts' => $posts]);
}
Lastly, update the <form> element for this Search function:
<form action="{{ route('search') }}">
<input type="search" class="form-control" placeholder="Find user here" name="search">
</form>
Now, when you navigate to http://localhost/posts/search, you'll get 20 Post records, ordered by created_at.
If you navigate to http://localhost/posts/search?search=example, you'll get up to 20 Post records, but only those that include example in their title.
You'll notice how similar that is to the index() method; so you can merge them to make your code a bit more "DRY" (Don't Repeat Yourself):
PostsController.php
public function index(Request $request) {
$postsQuery = Post::latest();
if ($request->has('search')) {
$postsQuery = $postQuery->where('title', 'like', '%' . $request->input('search') . '%');
}
$posts = $postQuery->paginate(20);
return view('posts.index', ['posts' => $posts]);
}
You don't need Route::get('/posts/search', ...); anymore. Instead, if you navigate to http://localhost/posts, you'll get the latest 20 Post records. If you navigate to http://localhost/posts?search=example, you'll get up to 20 Post records, ordered by created_at, but only those that include example in the title.

Get an attribute from one array in Mail blade Template

I cannot access to the attribute "price" in my Mail class in Laravel. I´ve got an error
Undefined index: price (View: C:\laragon\www\hr-english\resources\views\external__emails\registered-course.blade.php)
I think the problem is the controller. I had to do a query to the database to check the price of the course, because in my registered_courses table I have a foreign key related to courses which return to me the title of the course and its price.
When I got from the query those data and send the variables to the blade, it appears the error shown at the top.
My controller
public function store(Request $request)
{
try {
$data = $this->getData($request);
$email = Auth::user()->email;
$name = Auth::user();
$msg = $data;
$price = DB::table('courses')->select('price')->where('id', '=', $request['course_id'])->get();
RegisteredCourse::create($data);
Mail::to($email)->queue(new RegistCourse($msg, $email, $name, $price));
return redirect()->route('registeredCourse.index')
->with('sucess_message', 'Registered course was sucessfully added');
} catch(Exception $exception) {
return back()->withInput()
->withErrors(['unexpected_error' => 'Unexpected error occurred while trying to process your request.']);
}
}
My Mailable
class RegistCourse extends Mailable
{
use Queueable, SerializesModels;
public $subject = 'Registered Course';
public $msg;
public $email;
public $name;
public $price;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($msg, $email, $name, $price)
{
$this->msg = $msg;
$this->email = $email;
$this->name = $name;
$this->price = $price;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('external__emails.registered-course');
}
}
This is my blade template
<body>
<div class="container">
<div class="row">
<div>
<img src="{{asset('images/logo_leon.png')}}" alt="logo_leon" width="55" id="logo_login"><span style="color:gray">HOLYROOD ENGLISH SCHOOL</span>
</div>
<br>
<div>
<p>Thank you very much for your purchase, {{$name['name']}}. You have just registered in one of our courses.</p>
<p>
<table>
<tr>
<th>Name</th>
<th>Course</th>
<th>Date of purchase</th>
</tr>
<tr>
<td>{{$msg['course_id']}}</td>
<td>{{$price['price']}}</td>
</tr>
</table>
</p>
</p>
<p>See you in class. Surely we enjoy learning English.</p>
<p>If you have any questions, do not hesitate to contact us through any of our contact forms.</p>
<br>
<p>Equipo Holyrood English School</p>
</div>
</div>
</div>
</body>
</html>
In your code:
$data = $this->getData($request);
$email = Auth::user()->email;
$name = Auth::user(); // Should be Auth::user()->name (if name exists)
$msg = $data;
// The get() method returns an array even if there is one row.
$price = DB::table('courses')->select('price')->where('id', '=', $request['course_id'])->get();
So, $price should be $price[0]->price in the view or use first() method instead of get(). So, the name should be the property of the user model, Auth::user() will result in an object.
pay attention to the '->with' function that I use to send the datas to the view.
YOUR MAILING CLASS:
class SuccessBooking extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $booking;
public $user;
public $pdf_path;
public $rideCode;
public function __construct($user, $booking, $pdf_path, $rideCode)
{
$this->booking = $booking;
$this->user = $user;
$this->pdf_path = $pdf_path;
$this->rideCode = $rideCode;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('noreply#coride.com', "Co Ride Receipt")
->view('email/successbookinginvoice')
->attach(public_path($this->pdf_path))
->with([
'user' => $this->user,
'code' => $this->rideCode,
'path' => public_path($this->pdf_path),
'booking' => $this->booking,
]
);
}
}
YOUR BLADE TEMPLATE
#section('content')
{{--below we access a particular item in the object user--}}
<h5>Dear {{$user->firstName}}, congratulations on your successful booking.</h5>
{{--below we just access code, it's not an object--}}
<h5>Dear {{$code}}, congratulations on your successful booking.</h5>
#endsection

How to call out the "description" to replace the "parent_id" in laravel?

so here is my question, i have done everything and my senior request me to replace the parent_id now into description as the coder know what is the integer number represent but the users doesn't know. Here is the picture
My current view looks like !
As you can see inside the red column, there are two id :
1.( 999162, Testing3, Test3, 999161, active ) and
2.( 999163, testing4, test, 999162, active )
My desired output is the 1.( 999161 calls the 999161 description instead of id ).
Lets take 999163 as example : the desired output should be like 999163, testing4, test, test3, active.
I don't know how to call the description to replace the parent_id,can someone help ?
<div class="row">
<div class="col-md-12">
<br />
<h3 align="center">Category Data</h3>
<br />
#if($message = Session::get('success'))
<div class="alert alert-success">
<p>{{$message}}</p>
</div>
#endif
<div align="right">
Add
<br />
<br />
</div>
<table class="table table-bordered table-striped">
<tr>
<th>Id</th>
<th>Code</th>
<th>Description</th>
<th>Parent</th>
<th>Status</th>
<th>Action</th>
<th>Action</th>
</tr>
#foreach($category as $row)
<tr>
<td>{{$row['id']}}</td>
<td>{{$row['code']}}</td>
<td>{{$row['description']}}</td>
<td>{{$row['parent_id']}}</td>
<td>{{$row['status']}}</td>
<td>Edit</td>
<td>
<form method="post" class="delete_form" action="{{action('categoryController#destroy',$row['id'])}}">
{{ csrf_field() }}
{{ method_field('DELETE')}}
<input type="hidden" name="_method" value="DELETE" />
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</table>
</div>
</div>
Here is my categoryController.php coding
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class categoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$category =Category::all()->toArray();
return view('category.index',compact('category'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$parents = Category::all();//DB::table("bit_app_policy_category")->lists("name","id");
//Category::all();
return view('category.create',compact('parents'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'code' => 'required',
'description' => 'required',
'parent_id' => 'required',
'status' => 'required',
]);
$category = new Category([
'id' => $request->get('id'),
'code' => $request->get('code'),
'description' => $request->get('description'),
'parent_id' => $request->get('parent_id'),
'status' => $request->get('status'),
]);
$category->save();
return redirect()->route('category.create')->with('success', 'Data Added');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$category = Category::find($id);
return view('category.edit', compact('category','id'));
$parents = Category::all();//DB::table("bit_app_policy_category")->lists("name","id");
//Category::all();
return view('category.create',compact('parents'));
$parents = Category::all();//DB::table("bit_app_policy_category")->lists("name","id");
//Category::all
return view('category.edit',compact('parents'));
}
public function subRequest()
{
return view('subRequest');
}
public function subRequestPost()
{
$input = request()->all();
return response()->json(['success'=>'Got Submit Request.']);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request,[
'code' =>'required',
'description' =>'required',
'parent_id'=>'required',
'status'=>'required'
]);
$category = Category::find($id);
$category->code =$request->get('code');
$category->description =$request->get('description');
$category->parent_id =$request->get('parent_id');
$category->status =$request->get('status');
$category->save();
return redirect()->route('category.index')->with('success','Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$category = Category::find($id);
$category->delete();
return redirect()->route('category.index')->with('success','Data Deleted');
}
}
Category.php picture
Category.php picture
Suppose you have a Category model, add blew code to your Category model class.
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id', 'id');
}
Then, replace {{$row['parent_id']}} with {{$row->parent->description}} in your code.
This is the answer
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$tmp =Category::all()->toArray();
$category = array();
foreach ($tmp as $key => $row) {
$policy = Category::find($row['parent_id']);
$tmpResult = new Category();
$tmpResult-> id =$row['id'];
$tmpResult-> code =$row['code'];
$tmpResult-> description =$row['description'];
$tmpResult-> parent_id =$policy['description'];
$tmpResult-> status =$row['status'];
array_push($category, $tmpResult);
}
return view('category.index',compact('category'));
}

I just upgraded my laravel app to multiple auth guards, how do i get the value of the agent or admin authenticated user

I am using a multi auth guard for my laravel app and everything seems to be working fine....registration, login etc perfect. but i need to get values of an authenticated user of a specific guard in my views but it kept saying undefined property
Here is the code to my model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Agent extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname', 'lastname', 'aid', 'city', 'state', 'email', 'password', 'bankname', 'accountnumber',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
and for my view :
#extends('layouts.app')
#section('title')
OneNaira© Welcome Back {{ auth()->user()->firstname }}
#endsection
#section('footer')
<!--FOOTER-->
<div class="ui stackable pink inverted secondary pointing menu" id="footer">
<div class="ui container">
<a class="item">© OneNaira, 2019.</a>
<div class="right menu">
<a class="item">
<script>
var todaysDate = new Date();
document.write(todaysDate);
</script>
</a>
</div>
</div>
</div>
#endsection
and for the login controller
<?php
namespace App\Http\Controllers\Agent\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
class LoginController extends Controller
{
/**
* Show the login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('agent.auth.login',[
'title' => 'Welcome Back, Sign Into Your OneNaira Initiative Agent Dashboard',
'loginRoute' => 'agent.login',
'forgotPasswordRoute' => 'agent.password.request',
]);
}
/**
* Login the agent.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function login(Request $request)
{
$this->validator($request);
if(Auth::guard('agent')->attempt($request->only('aid','password'),$request->filled('remember'))){
//Authentication passed...
return redirect()
->intended(route('agent.dashboard'));
}
//Authentication failed...
return $this->loginFailed();
}
/**
* Logout the agent.
*
* #return \Illuminate\Http\RedirectResponse
*/
public function logout()
{
Auth::guard('agent')->logout();
return redirect()
->route('agent.login')
->with('status','Agent has been logged out!');
}
/**
* Validate the form data.
*
* #param \Illuminate\Http\Request $request
* #return
*/
private function validator(Request $request)
{
//validation rules.
$rules = [
'aid' => 'required|exists:agents,aid|min:8|max:191',
'password' => 'required|string|min:4|max:255',
];
//custom validation error messages.
$messages = [
'aid.exists' => 'These credentials do not match our records.',
];
//validate the request.
$request->validate($rules,$messages);
}
/**
* Redirect back after a failed login.
*
* #return \Illuminate\Http\RedirectResponse
*/
private function loginFailed()
{
return redirect()
->back()
->withInput()
->with('error','Login failed, please try again!');
}
}
I figured it out : {{ Auth::guard('agent')->user()->firstname }}

Laravel cashier "Unable to create Braintree customer" error

I am trying to create a subscription service using Laravel, Laravel Cashier and Braintree. I get the following error:
Unable to create Braintree customer: Unknown or expired payment_method_nonce.
CVV is required.
Expiration date is required.
Credit card number is required.
Credit card must include number, payment_method_nonce, or venmo_sdk_payment_method_code.
I've done the following in my HTML:
<form class="form-horizontal" role="form" method="POST" action="{{ route('register') }}">
<select name="plan" id="plan" class="form-control">
<option value="">Select plan</option>
<option value="free">Free plan - €0/month</option>
<option value="cool">Cool plan - €10/month</option>
<option value="epic">Epic plan - €100/month</option>
</select>
<div id="dropin-container"></div>
<input type="submit" class="btn btn-primary blue-button" value="Sign Up" style="margin-top: 6px;">
<!-- Load the Client component. -->
<script src="https://js.braintreegateway.com/js/braintree-2.31.0.min.js"></script>
<script>
braintree.setup('{{ $braintreeToken }}', 'dropin', {
container: 'dropin-container'
});
</script>
</form>
then I have the following RegisterController.php. The most important bit is in the create method:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/account';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the application registration form.
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showRegistrationForm()
{
$braintreeToken = \Braintree\ClientToken::generate();
return view('auth.register')
->with('braintreeToken', $braintreeToken)
->with('plan', 'none')
->with('route', 'register');
}
/**
* Handle a registration request for the application.
*
* #param Request|\Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'plan' => 'required|in:free,cool,epic'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$limit = 200;
$plan = 'free';
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'plan' => $plan,
'limit' => $limit,
'password' => bcrypt($data['password']),
]);
switch($data['plan'])
{
case 'cool':
$limit = 3000;
$plan = 'cool';
$planID = 'gt8m';
break;
case 'epic':
$limit = 32000;
$plan = 'epic';
$planID = '8v3g';
break;
}
$subscription = $user->newSubscription('main', $planID)->create($data['_token']);
if ($subscription)
{
$user->plan = $plan;
$user->limit = $limit;
$user->save();
}
return $user;
}
}
The error happens when I input the following credit card details (these are supposed to be the test credit card numbers used in the sandbox):
Credit card number: 4111 1111 1111 1111
Expiration date: 08/2018
CVV: 123
I've tried googling the error but nothing useful came up.
Problem was I was using the _token from the post data while I needed to use payment_method_nonce.

Resources