Laravel - can't access to error bag - laravel

I can't see any validation error, the $errors is always empty and I can't figured out why.
I have do this million times but in this project I do not see the problem.
Here the form:
#if( count( $errors ) > 0 )
<div class="alert alert-danger">
<ul>
#foreach( $errors->all() as $error )
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{{ Form::open(['url'=>route('admin.roles.store'), 'method'=>'post']) }}
<input type="text" name="name">
{{ Form::submit() }}
{{ Form::close() }}
Here my Controller method:
public function store(CreateRoleRequest $request)
{
$this->validate($request, [
'name' => 'required'
]);
}
The route use a middleware group:
'backend' => [
'auth',
\App\Http\Middleware\Boilerplate\CheckIfUserCanAccessToBackend::class
]
And this is the middleware:
<?php
namespace App\Http\Middleware\Boilerplate;
use Closure;
class CheckIfUserCanAccessToBackend
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = $request->user();
// Admin can access
if( $user->hasRole('admin') )
{
return $next($request);
}
// The user has the permission?
if($user->can('access_backend') ){
return $next($request);
}
// Can't access
return abort(403);
}
}
I have no idea about whats going on, any idea?

One thing that can cause this problem is adding web middleware manually to routes.php routes in Laravel 5.2.27 or higher.

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.

How to update the value of selected dropdown using Laravel?

I want to update selected drop down value and save that into database
in this code i cant update my drop down list value from database
my controller code
public function edit($product_id)
{
$all_categories = DB::table('tbl_category')->get();
$all_manufactures = DB::table('tbl_manufacture')->get();
$product = DB::table('tbl_product')
->where('product_id',$product_id)
->get()->first();
return View('admin.edit-product')->with([
'product'=>$product,
'all_categories'=>$all_categories,
'all_manufactures'=>$all_manufactures,
]);
}
my view code
<select id="brand_name" name="brand_name" data-rel="chosen">
#foreach($all_manufactures as $manufacture)
#if($manufacture->manufacture_status)
<option value="{{$manufacture->manufacture_id}}"> {{$manufacture->manufacture_name}}</option>
#endif
#endforeach
</select>
The edit method displays a form for editing.
/**
* Show the form for editing the specified resource.
*
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function edit(User $user)
{
$roles = Role::all();
return view('admin.users.form', [
'roles' => $roles,
'user' => $user
]);
}
You need update method
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = User::find($id);
$user->update($request->all());
$role = Role::findOrFail($request->roles);
$user->syncRoles([$role->id]);
return redirect()->route('users.index');
}
View
<form action="{{route('users.update', $user->id)}}" method="post">
#csrf
#method('PUT')
<select class="custom-select" name="roles">
#if ($roles)
#foreach($roles as $role)
<option {{ ((old('roles') == $role->id) or (isset($user) and $user->roles->pluck('id')->contains($role->id)) ) ? 'selected' : null }} value="{{$role->id}}">{{$role->display_name}}</option>
#endforeach
#endif
</select>
</form>

Setting a Flash error message with FormRequest

I am attempting to set and pass a flash message, when a form validation fails. When the validation passes, I am able to set Flash message in the controller.
I have tried to override the protected failedValidation() but I get an error.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Validator;
class UserRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'first_name' => 'required|string|min:2|max:50',
'last_name' => 'required|string|min:2|max:50',
'date_of_birth' => 'required|date',
'gender' => 'required|in:male,female'
];
}
/**
* Handle a failed validation attempt.
*/
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
Flash::error("Profile could not be saved!");
// alert()->error('oops ... error');
return parent::failedValidation($validator);
} }
error:
Symfony\Component\Debug\Exception\FatalThrowableError Class
'App\Http\Requests\Flash' not found
I am setting my view in app.blade.php as follows
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div> <!-- end .flash-message -->
you need to add use Flash; in the controller at the top after namespace declaration where you want to use the flash library methods.

Cant't edit or delete post in laravel project

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

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