I'm making a request to my laravel backend.
But the request gets treated as a GET instead of a POST, I can't find that the problem is..
here is the function:
this.$axios
.post('/create_car', {
data: formData
})
.then(res => {
this.status = true
this.isCreatingCar = false
})
and trying to recieve it in this controller function:
public function createCar(Request $request) {
$title = $request->title;
$previewText = $request->previewText;
$fuel = $request->fuel;
$gearbox = $request->gearbox;
$brand = $request->brand;
$model = $request->model;
$year = $request->year;
$miles = $request->miles;
$price = $request->price;
$carType = $request->carType;
$images = $request->images;
$car = Car::create([
'title' => $title,
'previewText' => $previewText,
'fuel' => $fuel,
'gearbox' => $gearbox,
'brand' => $brand,
'model' => $model,
'year' => $year,
'miles' => $miles,
'price' => $price,
'carType' => $carType
]);
// store each image
foreach($images as $image) {
$imagePath = Storage::disk('uploads')->put('/cars' . '/' . $car->id, $image);
carImage::create([
'carImageCaption' => $title,
'carImagePath' => 'uploads' . $imagePath,
'carId' => $car->id
]);
}
return response()->json(['errors' => false, 'data' => $car]);
}
here is the route:
Route::group(['middleware' => 'throttle:20.5'], function () {
Route::post('/create_car', 'CarController#createCar');
});
in the xamp log it seems like it sends two request first a POST and then a GET 3 seconds apart
Ok to fix this you need to call the route properly, since the route inside your api.php call it like this:
this.$axios
.post('/api/create_car', {
data: formData
})
.then(res => {
this.status = true
this.isCreatingCar = false
})
Related
I use laravel 8 & have 3 table:
Products, ProductPrice & ProductsPublisher:
this is my Products model for this relationship:
public function lastPrice(){
return $this->hasMany(ProductPrice::class)->where('status','active')->orderBy('created_at','DESC')->distinct('publisher_id');
}
and this is my productsPrice model for publisher relationship:
public function getPublisher(){
return $this->belongsTo(ProductsPublisher::class,'publisher_id');
}
now, i want to use laravel resource for my api, i wrote products resource:
public function toArray($request)
{
return [
'id' => $this->id,
'price' => lastPrice::make($this->lastPrice),
'status' => $this->status,
'slug' => $this->slug,
'title' => $this->title,
'description' => $this->description,
'txt' => $this->txt,
'lang' => $this->lang,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
but in lastPrice resource, when i wrote like this:
return [
'id' => $this->id,
'main_price' => $this->main_price
];
it give me this error:
Property [id] does not exist on this collection instance.
when i use this code:
return parent::toArray($request);
get response but because i need to use another relationship in my lastPirce for publishers, i cant use that code and should return separately my data.
What i should to do?
thanks
Edit 1:
this is my Controller Code:
$products = Product::where('id',$id)->where('slug',$slug)->where('status','confirm')->first();
if(!$products){
return $this->sendError('Post does not exist.');
}else{
return $this->sendResponse(new \App\Http\Resources\Products\Products($products), 'Posts fetched.');
}
and this is sendResponse & sendError:
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
thanks.
Edit 2:
i change my lastPrice Resource toArray function to this and my problem solved, but i think this isn't a clean way, any better idea?
$old_data = parent::toArray($request);
$co = 0;
$new_data = [];
foreach ($old_data as $index){
$publisher_data = Cache::remember('publisher'.$index['publisher_id'], env('CACHE_TIME_LONG') , function () use ($index) {
return ProductsPublisher::where('id' , $index['publisher_id'])->first();
});
$new_data[$co]['main_prices'] = $index['main_price'];
$new_data[$co]['off_prices'] = $index['off_price'];
$new_data[$co]['publisher'] = SinglePublisher::make($publisher_data);
$new_data[$co]['created_at'] = $index['created_at'];
$co++;
}
return $new_data;
So what I am trying to do is store notifications to the database with Notifiable, but I have a saveMany contents and I don't know how to declare the data in the notifications. getting a null from what I've declared like the picture below
this is my saveMany store
$post = new Post;
$post->user_id = Auth::guard('webcontrol')->user()->id;
$post->lob = $request->lob;
$post->type = 'post';
$post->category_id = $request->category_id;
$post->is_published = $request->is_published;
$post->published_at = ($request->published_at) ? $request->published_at : Carbon::now();
$post->metas = '{}';
$post->save();
$post->contents()->saveMany([
new PostContent([
'lang' => 'id',
'slug' => str_slug($request->contents['id']['title'], '-'),
'title' => $request->contents['id']['title'],
'body' => $request->contents['id']['body'],
'image' => $request->contents['id']['image'],
'tag' => $request->contents['id']['tag'],
'metas' => serialize($request->contents['id']['metas']),
]),
new PostContent([
'lang' => 'en',
'slug' => str_slug($request->contents['en']['title'], '-'),
'title' => $request->contents['en']['title'],
'body' => $request->contents['en']['body'],
'image' => $request->contents['en']['image'],
'tag' => $request->contents['en']['tag'],
'metas' => serialize($request->contents['en']['metas']),
])
]);
Notification::send($user, new OneSignalNotification($post));
dd('done');
this is my Notification
class OneSignalNotification extends Notification
{
use Queueable;
public $post;
public function __construct($post)
{
$this->post = $post;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'body' => $this->post['body'], //this is where i confused how to declare the saveMany contents so its not returning null
];
}
}
So I'm not sure what you're trying to achieve but the issue is with the fact that you want to retrieve the body from the post, but the way I see it, the $post doesn't have a body property. The PostContent seems to have the body property, but the problem is that you saved many PostContent to the same $post, so therefore there are multiple body properties, one for each PostContent. So that's why I would recommend use the first() method to get the first PostContent from $post and then return it. If you want to return all the body property, you would have to get all of them and add them into an array or a string, or whatever you want. I hope this makes sense.
You should try using this:
$post = new Post;
$post->user_id = Auth::guard('webcontrol')->user()->id;
$post->lob = $request->lob;
$post->type = 'post';
$post->category_id = $request->category_id;
$post->is_published = $request->is_published;
$post->published_at = ($request->published_at) ? $request->published_at : Carbon::now();
$post->metas = '{}';
$post->save();
$post->contents()->saveMany([
new PostContent([
'lang' => 'id',
'slug' => str_slug($request->contents['id']['title'], '-'),
'title' => $request->contents['id']['title'],
'body' => $request->contents['id']['body'],
'image' => $request->contents['id']['image'],
'tag' => $request->contents['id']['tag'],
'metas' => serialize($request->contents['id']['metas']),
]),
new PostContent([
'lang' => 'en',
'slug' => str_slug($request->contents['en']['title'], '-'),
'title' => $request->contents['en']['title'],
'body' => $request->contents['en']['body'],
'image' => $request->contents['en']['image'],
'tag' => $request->contents['en']['tag'],
'metas' => serialize($request->contents['en']['metas']),
])
]);
Notification::send($user, new OneSignalNotification($post->fresh()));
dd('done');
And then inside the Notification, like I said, we take the first PostContent from the $post and get it's body property:
class OneSignalNotification extends Notification
{
use Queueable;
public $post;
public function __construct($post)
{
$this->post = $post;
}
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'body' => $this->contents()->first()->body,
];
}
}
I've followed the documentation at https://laravel.com/docs/6.x/broadcasting step by step and make sure I copy and paste to be certain I don't make any mistake. I'm able to broadcast just fine and everything is working just fine. Because I'm unable to pass attributes, people in different roomId are counted as if they are all in the same room.
Here is the live example:
https://prayershub.com/worship/82 - 82 is the worship_id I would like to pass to:
Broadcast::channel('worship_presence_channel.{id}', function ($id) {
if(Auth()->check())
{
$profile = Auth()->user()->Profile;
$user = Auth()->user();
$data = [
'id' => $user->id,
'name' => $user->name,
'username' => $user->username,
'avatar' => config('app.storage').$profile->profile_image,
'url' => $profile->profile_url,
'favorite_bible_verse' => $profile->favorite_bible_verse
];
return $id;
}
});
From:
Echo.join(`worship_presence_channel.${id}`)
.here((users) => {
worshipers=users;
joinUser(worshipers);
$('.group-count').html(worshipers.length);
console.log(users);
})
.joining((user) => {
worshipers.push(user);
popupNewUser(user);
joinUser(worshipers);
$('.group-count').html(worshipers.length);
})
.leaving((user) => {
worshipers = worshipers.filter(function(obj) {
return (obj.id !== user.id);
});
popupLeaveUser(user);
joinUser(worshipers);
$('.group-count').html(worshipers.length);
});
I also have an event which seems to be unneccassary but it lools like this:
public function broadcastOn()
{
return new PresenceChannel('worship_presence_channel.58');
}
public function broadcastAs()
{
return 'worship_presence_channel.58';
}
Can anyone please, tell me what i'm doing wrong or if I get the whole thing just wrong. Please help!
I've figured it out, I've change the echo codes above to this:
Broadcast::channel('worship_presence_channel.{id}', function ($user, $id) {
if(Auth()->check())
{
$profile = $user->Profile;
$data = [
'id' => $user->id,
'name' => $user->name,
'username' => $user->username,
'avatar' => config('app.storage').$profile->profile_image,
'url' => $profile->profile_url,
'favorite_bible_verse' => $profile->favorite_bible_verse,
'worships_id' => $id
];
return $data;
}
});
I'm passing 2 parameters $user, $id and it works just as the doc said it would!!!
I'm trying to update an item that could have an image or change the one that is already there, when I only change the image or add one it doesn't update, but if I change or add an image along with something else like the name or description then it does update both things. I'm not sure why this is happening.
I'm sending it to the controller like this
submit(item) {
let data = new FormData();
data.append('file', this.imagen);
data.append('name', this.ruleForm.name);
data.append('summary', this.ruleForm.summary);
data.append('description', this.ruleForm.description);
data.append('price', this.ruleForm.price);
data.append('hours', this.ruleForm.hours);
data.append('min_grade', this.ruleForm.min_grade);
data.append('matery', this.matery);
data.append('remover', this.remover);
data.append('strict', this.strict);
this.$refs.ruleForm.validate((valid) => {
if (valid) {
this.loading = true;
this.$inertia.post('/courses/' + item.id, data)
.then(
() => {
this.$message({
type: 'success',
message: 'Guardado correctamente.'
});
this.loading = false
},
(res) => {
this.$message.error(parseError(res)[0]);
this.loading = false;
})
} else {
return false;
}
});
},
This is the full update function in the controller
public function update(CourseSaveRequest $request, $id)
{
Log::info($request);
$editCourse = Course::find($id);
$editCourse->name = $request->name;
$editCourse->summary = $request->summary;
$editCourse->description = $request->description;
$editCourse->price = $request->price;
$editCourse->hours = $request->hours;
$editCourse->min_grade = $request->min_grade;
if ($request->hasFile('file')) {
$this->removeImage($editCourse);
$image = $request->file('file');
$imageName = Uuid::generate(4)->string . '.' . $image->getClientOriginalExtension();
$editCourse->image = '/' . 'img/courses' . '/' . $imageName;
$request->file('file')->move('img/courses', $imageName);
}
$editCourse->save();
return back();
}
private function removeImage(Course $course){
if (!empty($course->image) && file_exists(public_path($course->image))) {
unlink(public_path($course->image));
}
}
Not sure if this is relevant but this is the CourseSaveRequest
public function rules()
{
$rules = [
'name' => 'required|unique:courses',
'summary' => 'required',
'price' => 'required|numeric|min:0',
'hours' => 'required|numeric|min:0',
'min_grade' => 'required|numeric|min:0'
];
if ($this->has('id')) {
$rules['name'] .= ',id,'.$this->get('id');
}
return $rules;
}
I suspect it's the unique rule on the name, you can ignore the current model instance on unique with the following
use Illuminate\Validation\Rule;
...
public function rules()
{
$rules = [
'name' => [
'required',
Rule::unique('courses')->ignore($this->id)
],
'summary' => 'required',
'price' => 'required|numeric|min:0',
'hours' => 'required|numeric|min:0',
'min_grade' => 'required|numeric|min:0'
];
return $rules;
}
I have this code I have written and tested. The first phase
mokkle_test(Request $request)
is working. I have issue with how to pass the result of the request to the second phase
First phase:
public function mokkle_test(Request $request)
{
$telco_match=['name'=>'Icell'];
$telco=Telco::where($telco_match)->first();
try{
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' =>$request->text,
'correlator' =>$request->correlator,
'serviceid' =>$request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$noti=new Notification_log();
$noti->error_message= (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
}catch(\Exception $e)
{
return $e->getMessage();
}
}
... and its working very well.
How do I pass the result of the response into another function shown below.
Second phase:
function subscribe($request,$telco)
{
try{
$client = new Client();
$response = $client->request(
'POST', $telco->billing_callback_2, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->password,
'amount' =>$request->amount,
'shortcode' => $request->shortcode
],
'headers' => [
'auth' => $telco->authorization,
'key' => $telco->key,
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
$amount = $request->amount;
$shortcode = $request->shortcode;
$noti=new Notification_log();
$noti->error_message=(string)$response;
$noti->msisdn=$request->msisdn;
$noti->product_id=$request->productid;
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
$request = array();
$request->text= "Weldone";
$request->amount = $amount;
$request->serviceid="100010";
$request->correlator="876543ghj";
$result_sms=self::mokkle_test($request);
return $result;
}catch(\Exception $e)
{
return $e;
}
}
I tried this, but nothing is happening
$result_sms=self::mokkle_test($request);
Kindly assist. How do I achieve my goal. Kindly assist me.
Here you can pass it to the other method
public function mokkle_test(Request $request)
{
$telco_match = ['name' => 'Icell'];
$telco = Telco::where($telco_match)->first();
try {
$client = new Client();
$response = $client->request(
'POST', $telco->send_call, [
'json' => [
'msisdn' => $request->msisdn,
'username' => $telco->username,
'password' => $telco->cpPwd,
'text' => $request->text,
'correlator' => $request->correlator,
'serviceid' => $request->serviceid,
'shortcode' => $request->shortcode
],
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
]
);
// Here you can pass it to the other method
this.subscribe($response, $telco); // <--- $response will be your "$request" parameter
$noti = new Notification_log();
$noti->error_message = (string)$response->getBody();
$noti->save();
$status = $response->getStatusCode();
$result = $response->getBody();
return $result;
} catch (\Exception $e) {
return $e->getMessage();
}
}