PostTooLarge Exception Laravel - laravel

I have uploaded 15mb image and it throws exception of PostTooLarge Exception instead of exception i have to show flash error message but could not get it.
below is the handler i have used for Handler.php it works great but not display flash message.
if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException)
{
return redirect()->route('users.add')->withFlashError('Image Size too large!');
}
then i tried validate of laravel for image in my controller which is as below
$validator = Validator::make($request->all(), [
'image' => 'max:4000',
]);
if ($validator->fails())
{
return redirect()->route('user')->withFlashError('Image size exceeds 4MB');
}
but still no luck
below is blade file with form:
<form method="post" action="{{route('users.submit')}}" id="adduser" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label class="col-form-label">User name*</label>
<input type="text" class="form-control" name="name" placeholder="User name" value="{{ old('name') }}">
</div>
<div class="form-group col-md-6">
<label class="col-form-label">User email*</label>
<input type="text" class="form-control" name="email" value="{{ old('email') }}" placeholder="User email" autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label class="col-form-label">Password*</label>
<input id="password" type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group col-md-6">
<label class="col-form-label">Confirm password</label>
<input type="password" class="form-control" name="confirmpassword" placeholder="Confirm password">
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="form-group col-md-6">
<label class="col-form-label">Phone number*</label>
<input type="text" class="form-control" name="mobile" value="{{ old('mobile') }}" placeholder="Phone Number">
</div>
<div class="col-md-6">
<label class="col-form-label">User role*</label>
<select name="role" class="form-control valid">
<option value="">Select Role</option>
<option {{ old('role')==3?'selected':'' }} value="3">Author</option>
<option {{ old('role')==5?'selected':'' }} value="5">Product Admin</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
<label class="col-form-label">User image</label>
<div class="card-body">
<div class="was-validated">
<label class="custom-file">
<input type="file" name="image" accept=".jpg, .png,.jpeg" id="file" class="custom-file-input">
<span class="custom-file-control"></span>
</label>
<ul class="preview" style="margin-top: 10px;">
</ul>
</div>
</div>
</div>
</div>
</div>
<button style="float: right;" type="submit" class="btn btn-primary" id="validateForm">Save</button>
</form>
and below is controller code :
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Validator;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = User::whereNotIn('role', array(1,4))->orderBy('id','DESC')->get();
return view('admin.users.index',compact('users'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.users.add');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data=$request->all();
$validate = Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
]);
if ($validate->fails()) {
return redirect('users/add')->withFlashError('Email already exists')->withInput();
}
if(isset($_FILES['image']))
{
$validator = Validator::make($request->all(), [
'image' => 'max:4000',
]);
if ($validator->fails())
{
//return redirect()->route('user')->withFlashError('Image size exceeds 4MB');
//return redirect()->route('user')->withErrors(['error' => 'Image size exceeds 4MB']);
//return redirect('users/add')->withFlashError('Image size exceeds 4MB')->withInput();
return redirect()->back()->withErrors(['error' => 'Image size exceeds 4MB']);
}
if(basename($_FILES['image']['name']) != "")
{
$target_path = base_path().'/public/user/';
$time=round(microtime(true));
$newfilename = $target_path .$time . '.jpg';
$target_path = $target_path .time().basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $newfilename))
{
$user_data['image'] =$time.'.jpg';
}
}
else
{
$user_data['image'] = "";
}
}
$insert_data = array
(
"name" => $data['name'],
"email" => $data['email'],
"password" => bcrypt($data['password']),
"mobile" => $data['mobile'],
"image" => $user_data['image'],
"role" => $data['role'],
"status" => 1
);
User::create($insert_data);
return redirect()->route('users')->withFlashSuccess('User added successfully');
}
/**
* 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)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = User::find($id);
$user->delete();
return redirect()->route('users')->withFlashSuccess('User deleted successfully');
}
public function delete($id)
{
$news = User::find($id);
$news->delete();
}
public function status($id)
{
$store=User::find($id);
if($store->status==1)
{
$status=0;
}
else
{
$status=1;
}
User::whereId($id)->update(array('status'=>$status));
return redirect()->route('users')->withFlashSuccess('User status changed');
}
public function saverole(Request $request)
{
$data=$request->all();
$string_role = implode(', ', $data['role']);
User::whereId($data['user_id'])->update(array('role'=>$string_role));
return redirect()->route('users')->withFlashSuccess('User role changed');
}
}

Change your validate line of code to this:
$this->validate(request(), [
'image' => 'max:4000'
],
[
'image.max' => 'Image size exceeds 4MB'
]);
And inside your view file, run this code to display the errors:
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif

Because the php.ini stands first while throwing exception, it will not carry forward that expectation to your defined errors.

Related

ArgumentCountError Too few arguments

I want to add data in database in Laravel, but I get error.
This is my Error:
ArgumentCountError
Too few arguments to function App\Http\Requests\Admin\Categories\StoreRequest::Illuminate\Foundation\Providers{closure}(), 0 passed in E:\xampp\htdocs\cylinders\cylinders\vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php on line 124 and exactly 1 expected
Here is my Route:
Route::post('', [CategoriesController::class, 'store'])->name('admin.categories.store');
my page:
<form action="{{ route('admin.categories.store') }}" method="post">
#csrf
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Slug</label>
<input type="text" class="form-control" name="slug">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title">
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary float-left">Save</button>
</div>
</form>
my Contoller:
public function store(StoreRequest $request)
{
$validatedData = $request->validate();
$createdCategory = Category::create([
'title' => $validatedData['title'],
'slug' => $validatedData['slug'],
]);
if(!$createdCategory){
return back()->with('failed', 'Failed to Create Category.');
}
return back()->with('success', 'Success to Create Category.');
}
my Request:
<?php
namespace App\Http\Requests\Admin\Categories;
use Illuminate\Foundation\Http\FormRequest;
class StoreRequest 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 [
'title' => 'required|min:3|max:128|unique:categories,title',
'slug' => 'required|min:3|max:128|unique:categories,slug',
];
}
}

submit form and redirect to another page after sending email with laravel

i can send the email without any problem, but form still like not submitted (refresh) or redirect to another page>>>>
this is my function to send an email:
function sendEmail(Request $request, $sendTo) {
$request->validate([
'name' => ['required', 'min:3'],
'email' => ['required', 'email'],
'subject' => ['required', 'min:3'],
'message' => ['required', 'min:3', 'max:300'],
]);
try {
$data = (object) $request->all();
event(new ContactEvent($data, $sendTo));
redirect()->back()->with('msg', "Email has sent successfully");
}catch(\Exception $e) {
redirect()->back()->with('msg', "Email not sent");
}
here the event:
class ContactEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public $data;
public $sendTo;
public function __construct($data, $sendTo)
{
$this->data = $data;
$this->data = $sendTo;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
and the listener:
class ContactListener
{
/**
* Create the event listener.
*
* #return void
*/
public function __construct()
{
}
/**
* Handle the event.
*
* #param \App\Events\ContactEvent $event
* #return void
*/
public function handle(ContactEvent $event)
{
Mail::to($event->sendTo)->send(new ContactMail($event->data));
}
and the email class:
class ContactMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $data;
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->subject($this->data->subject)->view('email.contact');
}
}
and the form to send an email:
<form action="{{ route('send-email', $info->email) }}" method="post" class="php-email-form">
#csrf
<div class="form-row">
<div class="form-group col-md-12">
<label for="name">Your Name</label>
<input type="text" name="name" class="form-control" id="name" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="form-group col-md-12">
<label for="name">Your Email</label>
<input type="email" class="form-control" name="email" id="email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<label for="name">Subject</label>
<input type="text" class="form-control" name="subject" id="subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<label for="name">Message</label>
<textarea class="form-control" name="message" rows="10" data-rule="required" data-msg="Please write something for us"></textarea>
</div>
<div class="mb-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><input type="submit" class="btn btn-dark rounded" value="Send"></div>
</form>
You are missing the return like so:
return redirect()->back()->with('msg', "Email has sent successfully");

laravel 8 Sorry! You have entered invalid credentials

I am using a custom Authentication in Laravel 8 and whenever I try to Enter a valid email/password am getting this error: Sorry! You have entered invalid credentials.
here is my code:
1#Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
use App\Models\User;
use Hash;
use Validator;
class AuthController extends Controller
{
/**
* Write code on Method
*
* #return response()
*/
public function index()
{
return view('auth.login');
}
/**
* Write code on Method
*
* #return response()
*/
public function registration()
{
return view('auth.register');
}
/**
* Write code on Method
*
* #return response()
*/
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('You have Successfully logged in');
}
return redirect("login")->withSuccess('Sorry! You have entered invalid credentials');
}
/**
* Write code on Method
*
* #return response()
*/
public function postRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'username' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("login")->withSuccess('Great! please login.');
}
/**
* Write code on Method
*
* #return response()
*/
public function dashboard()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('Opps! You do not have access');
}
/**
* Write code on Method
*
* #return response()
*/
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
/**
* Write code on Method
*
* #return response()
*/
public function logout() {
Session::flush();
Auth::logout();
return Redirect('login');
}
}
2#Login.blade.php:
#extends('layouts.layout')
#section('content')
<div class="login-form">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Login</div>
<div class="card-body">
#if (Session::get('success'))
<div class="alert alert-success" role="alert">
{{ Session::get('success') }}
</div>
#endif
<form action="{{ route('login.post') }}" method="POST">
#csrf
<div class="form-group row">
<label for="email_address" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<input type="text" id="email_address" class="form-control" name="email" required />
#if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<input type="password" id="password" class="form-control" name="password" required />
#if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Login
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
For registration it's working fine, the only problem is in Login form. Hope you can help.
First step: check your user model extends from Authenticable that main user model uses,
Second step:use bcrypt instead of Hash::make,
If solutions doesnt work send your model and config/auth.php for better answer

How to insert a row in Laravel given that one field does not have a default value?

I try to insert the session user id in form but it was show me error this:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into stocks (product_name, product_code, details, price, cost, quntity, updated_at, created_at) values (basmati Rice, 23432, dskljsdlkks;lk; ;ks;lvk, 40, 75, 100kg, 2019-09-09 08:43:12, 2019-09-09 08:43:12))
I think error on this line of code which I used for store the session id
<input type="hidden" name="user_id"
value="{{ $request->session()->put('user',$request->input('id')) }}"
> class="form-control">
This is my create blade page, which I make a form and try to insert the form fields.
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-md-12">
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
#if(\Session::has('success'))
<div class="alert alert-success">
<p>{{ \Session::get('success') }}</p>
</div>
#endif
<div class="card">
<div class="card-header">
<h5 class="title">Add New Product on Stock</h5>
</div>
<div class="card-body">
<form method="post" action="{{url('stock')}}">
{{csrf_field()}}
<div class="row">
<div class="col-md-6 pr-1">
<div class="form-group">
<label>Product Name</label>
<input type="text" name="user_id"
value="{{Auth::user()->id }}" class="form-control">
<input type="text" name="product_name" class="form-control" placeholder="Enter Product Name" />
</div>
</div>
<div class="col-md-6 pl-1">
<div class="form-group">
<label>Product Code</label>
<input type="text" name="product_code" class="form-control" placeholder="Enter product_code" />
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-md-4 pr-1">
<div class="form-group">
<label>Price</label>
<input type="text" name="price" class="form-control" placeholder="Enter price" />
</div>
</div>
<div class="col-md-4 px-1">
<div class="form-group">
<label>Cost</label>
<input type="text" name="cost" class="form-control" placeholder="Enter cost" />
</div>
</div>
<div class="col-md-4 pl-1">
<div class="form-group">
<label>Quantity</label>
<input type="text" name="quntity" class="form-control" placeholder="Enter quntity" />
</div>
</div>
</div>
</br>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Details</label>
<input type="text" name="details" class="form-control" placeholder="Enter details" />
</div>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" />
</div>
</form>
</div>
</div>
#endsection
this is my controller file of stock
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Stock;
use Auth;
class StockController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$stocks = Stock::all()->toArray();
return view('stock.index', compact('stocks'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('stock.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, [
'user_id' =>'required',
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = new Stock([
'user_id' => Auth::user()->user_id,
'product_name' => $request->get('product_name'),
'product_code' => $request->get('product_code'),
'details' => $request->get('details'),
'price' => $request->get('price'),
'cost' => $request->get('cost'),
'quntity' => $request->get('quntity')
]);
$stock->save();
return redirect()->route('stock.index')->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)
{
$stock = Stock::find($id);
return view('stock.edit', compact('stock', 'id'));
}
/**
* 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, [
'product_name' => 'required',
'product_code' => 'required',
'details' => 'required',
'price' => 'required',
'cost' => 'required',
'quntity' => 'required'
]);
$stock = Stock::find($id);
$stock->product_name = $request->get('product_name');
$stock->product_code = $request->get('product_code');
$stock->details = $request->get('details');
$stock->price = $request->get('price');
$stock->cost = $request->get('cost');
$stock->quntity = $request->get('quntity');
$stock->save();
return redirect()->route('stock.index')->with('success', 'Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$stock = Stock::find($id);
$stock->delete();
return redirect()->route('stock.index')->with('success', 'Data Deleted');
}
}
You don't have to use the $request->input('id') to get the user id .
Simply use
Session::flash(Auth::user()->id);
For your code ,
<input type="hidden" name="user_id"
value="{{Auth::user()->id, Session::flash(auth::user()->id) }}"
> class="form-control">
And in your controller ,
when you are trying to save the user_id variable ,
EDIT ::::
$stock = new Stock([
'user_id' => Auth::user()->id,
'product_name' => $request->get('product_name'),
'product_code' => $request->get('product_code'),
'details' => $request->get('details'),
'price' => $request->get('price'),
'cost' => $request->get('cost'),
'quntity' => $request->get('quntity')
]);
Use the session variable to store ,.
Or you can directly store the user_id using Auth::user()->id in that line ,
'user_id' => Auth::user()->user_id,
change this:
$request->session()->put('user',$request->input('id'))
to like this:
Session::set('user',$request->input('id'));
Make attention, you need pass the $request to your view, so you can use the request data. Otherwise create a variable $user_id and pass it to your view blade. in this case you can do:
Session::set('user',$user_id);

Trying to get property 'id' of non-object (View: E:\xampp\htdocs\mini_blog\resources\views\admin\posts\edit.blade.php)

Trying to get property 'id' of non-object
how to fix the bug, please explain to me, someone
edit.blade.php
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-header text-center">Edit Post : {{$posts->title}}</div>
<div class="card-body">
#if(count($errors)>0)
<ul class="list-group alert">
#foreach($errors->all() as $error)
<li class="list-group-item text-danger">
{{$error}}
</li>
#endforeach
</ul>
#endif
<form action="{{route('post.update',['id'=>$posts->id])}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" name="title" placeholder="Enter" class="form-control" value="{{$posts->title}} ">
</div>
<div class="form-group">
<label for="image">Featured Image</label>
<input type="file" name="image" class="form-control">
</div>
<div class="form-group">
<label for="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $cat)
<option value="{{$cat->id}}"
#if($posts->cat->id== $cat->id)
selected
#endif
>{{$cat->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="tag">Select Tags</label>
#foreach($tag as $tags)
<div class="checkbox">
<label><input type="checkbox" name="tags[]" value="{{$tags->id}}"
#foreach($posts->tags as $t)
#if($tags->id==$t->id)
checked
#endif
#endforeach
>{{$tags->tag}}</label>
</div>
#endforeach
</div>
<div class="form-group">
<label for="content">Description</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$posts->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
#endsection
PostController.php
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-header text-center">Edit Post : {{$posts->title}}</div>
<div class="card-body">
#if(count($errors)>0)
<ul class="list-group alert">
#foreach($errors->all() as $error)
<li class="list-group-item text-danger">
{{$error}}
</li>
#endforeach
</ul>
#endif
<form action="{{route('post.update',['id'=>$posts->id])}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" name="title" placeholder="Enter" class="form-control" value="{{$posts->title}} ">
</div>
<div class="form-group">
<label for="image">Featured Image</label>
<input type="file" name="image" class="form-control">
</div>
<div class="form-group">
<label for="category">Select a Category</label>
<select name="category_id" id="category" class="form-control">
#foreach($categories as $cat)
<option value="{{$cat->id}}"
#if($posts->cat->id== $cat->id)
selected
#endif
>{{$cat->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="tag">Select Tags</label>
#foreach($tag as $tags)
<div class="checkbox">
<label><input type="checkbox" name="tags[]" value="{{$tags->id}}"
#foreach($posts->tags as $t)
#if($tags->id==$t->id)
checked
#endif
#endforeach
>{{$tags->tag}}</label>
</div>
#endforeach
</div>
<div class="form-group">
<label for="content">Description</label>
<textarea name="content" id="content" cols="5" rows="5" class="form-control"> {{$posts->content}}</textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Submit" class="btn btn-primary">
</div>
</form>
</div>
</div>
#endsection
Trying to get property 'id' of non-object when I select category its not selected and show id is non-object
PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use App\Post;
use App\Tag;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.posts.index')->with('posts',Post::all());
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$categories=Category::all();
if($categories->count()==0){
Session::flash('info','You must have some categories before attempt post.');
return redirect()->back();
}
return view('admin.posts.create')->with('category',$categories)->with('tags',Tag::all());
}
/**
* 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|max:255',
'image'=>'required|image',
'content'=>'required',
'category_id'=>'required',
'tags'=>'required'
]);
$images=$request->image;
$image_new_name=time().$images->getClientOriginalName();
$images->move('uploads/posts',$image_new_name);
$post=Post::create([
'title'=>$request->title,
'image'=>$request->image,
'content'=>$request->content,
'image'=>'uploads/posts/'.$image_new_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
$post->tags()->attach($request->tags);
Session::flash('success','Post Created Successfully');
return redirect()->back();
}
/**
* 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)
{
$post=Post::find($id);
return view('admin.posts.edit')->with('posts',$post)
->with('categories',Category::all())
->with('tag',Tag::all());
}
/**
* 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,[
'title'=>'required',
'content'=>'required',
'category_id'=>'required',
]);
$post=Post::find($id);
if ($request->hasFile('image'))
{
$featured=$request->image;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts',$featured_new_name);
$post->image='uploads/posts/'.$featured_new_name;
}
$post->title=$request->title;
$post->content=$request->content;
$post->category_id=$request->category_id;
$post->save();
$post->tags()->sync($request->tags);
Session::flash('success','Your Post Updated Successfully');
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post=Post::find($id);
$post->delete();
Session::flash('success','Post was just trashed');
return redirect()->back();
}
public function trashed(){
$post=Post::onlyTrashed()->get();
return view('admin.posts.trashed')->with('posts',$post);
}
public function kill($id){
$post=Post::withTrashed()->where('id',$id)->first();
$post->forceDelete();
Session::flash('success','Post deleted permanently');
return redirect()->back();
}
public function restore($id){
$post=Post::withTrashed()->where('id',$id)->first();
$post->restore();
Session::flash('success','Post Restore ');
return redirect()->route('posts');
}
}
Make sure that categories, tags are not empty, also the Postrelationships are true.

Resources