Data stored in cache is null (Cache driver: array) - caching

I tried to store data in cached but when I retrieved the cached it returns null.
My cache driver is CACHE_DRIVER=array
and here is my controller...
public function index(Request $request){
view()->share('page_sub', 'Webhhook');
$data = Cache::get('repo');
dd($data);
return view('webhook.index', compact('data'));
}
public function handle(Request $request){
// $data = $request;
$admins = User::whereHas('roles', function($q){$q->whereIn('roles.name', ['superadmin']);})->get();
$data = [
'id' => $request['repository']['id'],
'name' => $request['repository']['name'],
'tags_url' => $request['repository']['tags_url'],
'archive_url' => $request['repository']['archive_url'],
'updated_at' => $request['repository']['updated_at'],
];
$now = \Carbon\Carbon::now();
$repo_data = cache('repo');
\Log::info($repo_data);
if ($data['updated_at'] != $repo_data['updated_at']) {
Cache::put('repo', $data, $now->addMonth(1));
}
foreach($admins as $user){
$user->notify(new WebhookNotification($repo_data));
}
}
when I dd($data) from this $data = Cache::get('repo'); the result is null
Any ideas?
Thank you.

CACHE_DRIVER=array only stores data in cache for functions used in same request and expires as soon as response is sent to browser.
If you want to access cache data in multiple request you can use CACHE_DRIVER=file this will save your data in files which can be accessed later.

Related

Laravel how to pass request from controller to resource collection?

I will pass a parameter in the request. The query won't change. How can I pass the request to SurveyResouce
public function getAllSurveys(\Illuminate\Http\Request $request) {
$surveys = DB::table('surveys')
->select('id', 'survey_name')
->get();
return response()->json([
'error' => false,
'data' => SurveyResource::collection($surveys)
],
}
I want get the request parameters in the resource
public function toArray($request) {
$controller = new SurveyController(new SurveyRepository());
return [
'question' => $request->has('ques') ? $request->input('ques'):'',
];
}
You can try by directly using request() helper function. Like request('parameter');

Make request (pass data) from Command File to Controller in Lumen/Laravel

i get data (query) in command file and want to pass to controller via API (route)
here my request code in command file :
$request = Request::create('/create_data_account', 'post', ['data'=>$data]);
$create = $app->dispatch($request);
this is the route :
$router->post('/create_data_account', 'APIController#create_account_data_api');
and my controller :
public function create_account_data_api(Request $request)
{
$count = 0;
foreach ($data as $key => $value) {
$insert = Account::create([
'account_name' => $value->account_name,
'type' => $value->type,
'role_id' => $value->role_id
]);
if($insert){
$count++;
}else{
return $response = ['result'=>false, 'count'=>$count, 'message'=>'Internal error. Failed to save data.'];
}
}
return $response = ['result'=>true, 'count'=>$count, 'message'=>'Account data saved Successfully'];
}
i'm confused why passing data to controller not working with that code. anyone can give me solution ? Thanks
As you are making the request with ['data'=>$data]. That means all the data is contained on the key data of your array. So before the foreach loop, you need to add a declaration statement $data = $request->input('data'); to get data in $data variable.

GuzzleHttp\Exception\InvalidArgumentException IDN conversion failed

after i added product data into database, this error page show me instead of routing to product page.
But, data is successful inserted.
ProductsController.php
public function store(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('add', app($dataType->model_name));
// Validate fields with ajax
$val = $this->validateBread($request->all(), $dataType->addRows);
if ($val->fails()) {
return response()->json(['errors' => $val->messages()]);
}
if (!$request->ajax()) {
$requestNew = $request;
$requestNew['price'] = $request->price * 100;
$data = $this->insertUpdateData($requestNew, $slug, $dataType->addRows, new $dataType->model_name());
event(new BreadDataAdded($dataType, $data));
$this->updateProductCategories($request, $data->id);
return redirect()
->route("voyager.{$dataType->slug}.index")
->with([
'message' => __('voyager.generic.successfully_added_new')." {$dataType->display_name_singular}",
'alert-type' => 'success',
]);
}
}
Plz help me

Laravel: Database is not storing my image but showing me only array

I am new to Laravel. I have been trying to save an image to the database. Here is my controller method that I am trying for storing the image
public function store(Request $request){
//validation for form
$validate= $request->validate([
'name' => 'required|min:2|max:140',
'position' => 'required|min:2|max:140',
'salary' => 'required|min:2|max:140',
'joining_date' => ''
]);
//saving form
if($validate){
$employee=new Employee;
$employee->name =$request->input('name');
$employee->company_name =$request->input('company_name');
$employee->position =$request->input('position');
$employee->salary =$request->input('salary');
$employee->joining_date =$request->input('joining_date');
$employee->user_id= auth()->user()->id;
//image saveing method
if($request->hasFile('image')){
$image= $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Employee::make($image)->resize(300, 300)->save( public_path('/employee/images/' . $filename ) );
$employee->image= $filename;
}else{
return $request;
$employee->image= '';
};
$employee->save();
//redirecting to Employee list
return redirect('/employee/details')->with('success','Employee Added');
}
I could save the form while there was no image and redirect it to the details page. but now when I try with the image, instead of saving it and redirecting to the details route, it returns me to the array of row of database like this:
{
"_token": "FPHm9AKuEbRlqQnSgHhjPnCEKidi2xr0usgp7RoW",
"name": "askfjlk",
"company_name": "laksjsflkj",
"position": "lkasjfkl",
"salary": "35454",
"joining_date": "4654-05-06",
"image": "testing.png"
}
What did I do wrong here? please help me out this newb.
You are returning $request object and Laravel does automatic JSON response.
if ($request->hasFile('image')){
// image storing logic which obviously is never started because expression above is false
} else {
return $request; // There is your problem
$employee->image= '';
};
You need to check why you are getting false on $request->hasFile('image').
Also, one tip because you are new to Laravel:
// When you are accessing to $request object you can use dynamic propertes:
$employee->company_name = $request->input('company_name');
// is the same as
$employee->company_name = $request->company_name;
You can check it there: Laravel docs in the section: Retrieving Input Via Dynamic Properties

Validation for form not checking partly

I have a Laravel program that saves form data and uploads a few pictures. In the validation, there are two rules. The image is required and it has to be of image type (jpg, jpeg, png). However, the validation only checks for the filetype and does not check for 'required'. Even if there is no image, it allows the user to submit. Why?
public function updateImages(Request $request, $id)
{
$validatedData = $request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg|max:2048',
],
[
'image.*.image' => 'Format Error: Please uplaod image in a png or jpg format',
]);
$item = Post::find($id);
$existing_count = Photo::where('post', $item->id)->count();
$countrequest = sizeof($request->file('image'));
$count = $existing_count + $countrequest;
if ($count >= 6) {
return back()
->withInput()
->withErrors(['Only 5 images can be uploaded!']);
}
$upload = $this->imageUpload($item, $request);
return redirect()->back()->with('message', 'Image Updated');
}
Apply require with image.*. Eg.-
image.*' => 'require|image|mimes:jpeg,png,jpg|max:2048',
Try this solution. It will work.
You can use Laravel Request Validation
To create a form request class
php artisan make:request ImageUpdateRequest
Go to app/Http/Requests add the rules
public function authorize()
{
return true;
}
public function rules()
{
return [
'image' => 'required|image|mimes:jpeg,png,jpg|max:2048'
];
}
On your controller
use App\Http\Request\ImageUpdateRequest;
public function updateImages(ImageUpdateRequest $request, $id)
{
$item = Post::find($id);
$existing_count = Photo::where('post',$item->id)->count();
$countrequest = sizeof($request->file('image'));
$count= $existing_count+$countrequest;
if ($count >= 6 ){
return back()
->withInput()
->withErrors(['Only 5 images can be uploaded!']);
}
$upload = $this->imageUpload($item, $request);
return redirect()->back()->with('message', 'Image Updated');
}

Resources