xxxxxxxxxx
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'user_id' => 'exists:users,id',
]);
if ($validator->fails()) {
// Handle validation failure
}
// Validation passed, continue with your logic
}
xxxxxxxxxx
$request->validate([
'id' => 'required|unique:users',
// . 'id' => 'required|exists:App\User,id', This works laravel 6 and up
'body' => 'required',
]);
xxxxxxxxxx
//create a rule if you're going to use it again
php artisan make:rule CompanyPackageNotExistsRule
//FormRequest
'company_id' => ['required','integer','exists:companies,id', new CompanyPackageNotExistsRule()],
public function passes($attribute, $value)
{
return !CompanyPackage::where('company_id', $value)->exists();
}
public function message()
{
return 'You have already purchased a package.';
}
//or use directly
'company_id' => ['required','integer','exists:companies,id', function ($attribute, $value, $fail) {
if (CompanyPackage::where('company_id', $value)->exists()) {
$fail('You have already purchased a package.');
}
}]
xxxxxxxxxx
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function testStore(Request $request)
{
// Validate and store the blog post...
}
}
xxxxxxxxxx
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* @return \Illuminate\View\View
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
}
}