Laravel cant seem to implement search properley - laravel

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.

Related

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'));
}

In my laravel blog website, i want to display post author as the logged in admin and display in the post view

I've been having issues displaying author of a post. I created a one to many relationship between admin and post. But in my view (post.blade.php) one admin is showing in all posts as an author rather than the respective admins who created the post. It only assigns the newest admin as the author to all other posts made by different admins, how do i get rid of this error please?.[When i die and dumb post, it shows the admin_id perfectly.
PostController for post that is shown in the front end, controller handling what visitors sees when they visit the page:
class PostController extends Controller
{
public function post(Request $request, post $post//provided from the post model, category $category)
{
$posts = post::all();
$postss = post::where('status', 1)->orderBy('created_at', 'asc')->limit(1)->get();
$categories = $category::all();
//dd ($post);
return view('user/layout/post', compact('post', 'posts','categories', 'postss'));
}
}
PostController for admin side:
class PostController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = post::all(); //displays all posts in the admin section
return view('admin.post.list', compact('posts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
if (Auth::user()->can('posts.create')) {
//this function is to permit admin to create posts
$categories = category::all();
return view('admin.post.post', compact('categories'));
}
return redirect(route('admin.home'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request) //validates and stores the posts
{
$this -> validate($request, [
'title' => 'required',
'subtitle' => 'required',
'slug' => 'required',
'body' => 'required',
'image' => 'required',
]);
if($request->hasFile('image')){
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $image);
Image::make($image)->save($location);
return response()->json(['uploaded' => '/images/'.$image]);
}
$post = new post;
$post -> title = $request -> title;
$post -> subtitle = $request -> subtitle;
$post -> body = $request -> body;
$post -> slug = $request -> slug;
$post -> image = $filename;
$post -> status = $request -> status;
$post->admin_id = Auth::user()->id;
$post -> save();
$post -> categories() -> sync($request -> categories );
return redirect(route('post.index'));
}
}
This is my post model
<?php
namespace App\Model\user;
use Illuminate\Database\Eloquent\Model;
use App\Model\admin\admin;
use CyrildeWit\EloquentViewable\Viewable;
class post extends Model
{
use Viewable;
public function categories()
{
return $this->belongsToMany('App\Model\user\category', 'category_posts')->withTimeStamps();
}
public function admin()
{
return $this->belongsTo(admin::class);
}
public function getRouteKeyName()
{
return 'slug';
}
}
This is my post.blade.php:
<div class="col-md-7">
<article class="post-single">
<div class="post-body">
<strong> created at {{ date('F d, Y', strtotime($post->created_at)) }}</strong>
#foreach($post->categories as $category)
<strong class="pull-right" style="margin-right:20px">
{{$category -> name}}
</strong>
<br>
#endforeach
{!!htmlspecialchars_decode($post->body)!!}
</div>
</article>
<div class="writter-section">
<div class="container">
<div class="row">
<div class="col-md-7 col-lg-offset-1">
<div id="writter">
<ul class="writter-list">
<li>
<div class="wriiter">
<div class="writter-pic">
<img src="{{ asset('author_images/'. $post->admin->Adminimage)}}">
</div>
<div class="writter-text">
<h4 class="upper"> {{ $post->admin->id}} </h4>
<h5> {{ $post->admin->description}}</h5>
<p> </p>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
This is the posts database:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('admin_id')->unsigned();
$table->string('title',255);
$table->string('subtitle',100);
$table->string('slug',100);
$table->text('body');
$table->boolean('status')->nullable();
$table->string('image');
$table->timestamps();
$table->foreign('admin_id')
->references('id')->on('admins')
->onDelete('cascade');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
This is the admins database
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('Adminimage');
$table->string('password');
$table->string('description');
$table->string('phone');
$table->boolean('status');
$table->timestamps();
$table->string('description');
$table->rememberToken();
});
}
In the postblade view new authors overwrites the previous original authors. So If i have 6 posts, all 6 posts have an author instead of it's original author. For better understanding you can check this link(the link to the website with the error) blog.dodo.ng, thank you all
I figured what was wrong with my blog post, I was passing a wrong value of post in my post.blade.php file. I was using the value of $postss in my Post controller for user rather than the value of $post from post $post in the post function (first function in my post controller for user). Thank you all

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 - can't access to error bag

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.

Resources