Axios Delete not working - laravel

In my CRUD webapp based on Laravel 5.6 and Vue.js 2 Add, Edit and Show are working fine. But Delete is not working because axios.delete is not sending id to controller. Console.log in Home.vue is showing correct id and key values. Following is the code and result what I am getting in controller. Please tell my mistake. Also do I really need a Route for delete in web.php?
Controller
public function destroy(Sms $sms)
{
$myfile = fopen("newfile.txt", "w", true) or die("Unable to open file!");
$txt = "Print_r: ". print_r($sms) ."\r\nID: ". $sms->id;
//fwrite($myfile, $txt);
fwrite($myfile, print_r($sms, TRUE));
//die();
Sms::where('id',$sms->id)->delete();
}
Home.vue
del(key,id){
if(confirm("Are you sure?")){
this.loading = !this.loading
/*axios.delete(`/sms/${id}`)*/
axios.delete(`sms/${id}`, {params: {id: `${id}`}})
.then((response)=> {this.lists.splice(key,1);this.loading = !this.loading})
.catch((error)=> this.errors = error.response.data.errors)
console.log(`KEY:${key} ID:${id}`);
}
}
web.php
Route::delete('sms/{id}', 'smsController#destroy');
newfile.txt
App\Sms Object
(
[hidden:protected] => Array
(
[0] => created_at
[1] => updated_at
)
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array
(
)
[withCount:protected] => Array
(
)
[perPage:protected] => 15
[exists] =>
[wasRecentlyCreated] =>
[attributes:protected] => Array
(
)
[original:protected] => Array
(
)
[changes:protected] => Array
(
)
[casts:protected] => Array
(
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[appends:protected] => Array
(
)
[dispatchesEvents:protected] => Array
(
)
[observables:protected] => Array
(
)
[relations:protected] => Array
(
)
[touches:protected] => Array
(
)
[timestamps] => 1
[visible:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
)

try to change axios.delete to axios.post, and add a _method field with the value delete in the data to be sent. like so
axios.post(`sms/${id}`, {params: {id: `${id}`}, _method: 'delete'})

Related

How can I check that file returned by laravel-medialibrary getUrl method really exists?

In laravel 8 app I use spatie/laravel-medialibrary 9
and how can I check that file returned by getUrl really exists under storage in code :
foreach (Auth::user()->getMedia('avatar') as $mediaImage) {
\Log::info( varDump($mediaImage, ' -1 $mediaImage::') );
return $mediaImage->getUrl();
}
?
$mediaImage var has data like:
Array
(
[id] => 11
[model_type] => App\Models\User
[model_id] => 1
[uuid] => 2fb4fa16-cbdc-4902-bdf5-d7e6d738d91f
[collection_name] => avatar
[name] => b22de6791bca17184093c285e1c4b4b5
[file_name] => avatar_111.jpg
[mime_type] => image/jpg
[disk] => public
[conversions_disk] => public
[size] => 14305
[manipulations] => Array
(
)
[custom_properties] => Array
(
)
[generated_conversions] => Array
(
)
[responsive_images] => Array
(
)
[order_column] => 1
[created_at] => 2021-12-30T14:08:11.000000Z
[updated_at] => 2021-12-30T14:08:11.000000Z
[original_url] => http://127.0.0.1:8000/storage/Photos/11/avatar_111.jpg
[preview_url] =>
)
Looks like nothing about file under storage...
Thanks!
Method :
File::exists($mediaImage->getPath());
helped me!

displaying particular data from entire json using laravel

I have an issue in printing the data from the below json in laravel. Find below the json data and help me with this.
DarthSoup\Cart\Item Object ( [rowId] => 76cc22e6f533b8ef3d08e6eca0f110b4 [id] => 61XJrpB7CgiYSRCX6hR78wCEABhjLI7jNLzPyDrkYA3LyIVisz [name] => linux [quantity] => 1 [price] => 109 [options] => DarthSoup\Cart\CartItemOptions Object ( [items:protected] => Array ( [package] => Super Lite ) ) [subItems] => DarthSoup\Cart\SubItemCollection Object ( [items:protected] => Array ( ) ) [created_at:protected] => Carbon\Carbon Object ( [date] => 2018-06-22 05:41:18.674548 [timezone_type] => 3 [timezone] => UTC ) [updated_at:protected] => Carbon\Carbon Object ( [date] => 2018-06-22 05:41:18.674574 [timezone_type] => 3 [timezone] => UTC ) [associatedModel:protected] => [taxRate:protected] => 19 ) 1
From the above json how to display the "price=>109" and "package=>super Lite"...
I'm getting an error as "Cannot use object of type DarthSoup\Cart\Item as array"
Find below the controller Code:
public function addCart(Request $request)
{
$name = $request->input();
$hosting=$name['hosting'];
$package=$name['package'];
$price=$name['price'];
$response=Cart::add(['id'=>str_random(50) ,'name' => $hosting, 'quantity' => 1, 'price' => $price, 'options' => ['package' => $package]]);
//dd($response);
return Cart::content();
return view('main.cart',Cart::content());
}
Blade file is given below:
#foreach($response->options as $option){
{{$option['name']}}
}
#endforeach
In my output I need to display the value of price,name and package...please help me to solve this error...
First this is not json, it is php object
if your variable name is $item then you can try this
$item->rowId;
$item->id;
$item->name;
$item->price;
foreach($item->options as $option){
echo $option->package;
}

Unable to access created_at and updated_at date in laravel with mongodb

I am having trouble accessing created_at and updated_at properties in a Laravel model using MongoDB. My date format in the database is as follows:
"created_at" : {
"sec" : NumberInt(1475126325),
"usec" : NumberInt(840000)
},
"updated_at" : {
"sec" : NumberInt(1475126325),
"usec" : NumberInt(840000)
},
I get the following result from MongoDB query:
App\Modules\Admin\Models\Segment Object
(
[table:protected] => tbl_segment
[timestamps] => 1
[fillable:protected] => Array
(
[0] => name
[1] => created_at
[2] => updated_at
)
[collection:protected] =>
[primaryKey:protected] => _id
[parentRelation:protected] =>
[connection:protected] =>
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[attributes:protected] => Array
(
[_id] => MongoDB\BSON\ObjectID Object
(
[oid] => 57ecbefe15285745ba039871
)
[created_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
[updated_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
)
[original:protected] => Array
(
[_id] => MongoDB\BSON\ObjectID Object
(
[oid] => 57ecbefe15285745ba039871
)
[created_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
[updated_at] => Array
(
[sec] => 1475133182
[usec] => 832000
)
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[dates:protected] => Array
(
)
[dateFormat:protected] =>
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
[wasRecentlyCreated] =>
)
When I try to access created_at date, I get the following error:
ErrorException in Model.php line 2983:
preg_match() expects parameter 2 to be string, array given
I had similar issue after updating laravel package (jessengers) for mongodb.You can try - Find following lines
if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value)) {
in Model.php found at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
and replace it by
if (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value['sec'])) {
in vendor/nesbot/carbon/src/Carbon/Carbon.php replace createFromFormat() function with -
public static function createFromFormat($format, $time, $tz = null)
{
$time = date('Y-m-d H:i:s' , $time['sec']);
if ($tz !== null) {
$dt = parent::createFromFormat($format, $time, static::safeCreateDateTimeZone($tz));
} else {
$dt = parent::createFromFormat($format, $time);
}
if ($dt instanceof DateTime) {
return static::instance($dt);
}
$errors = static::getLastErrors();
throw new InvalidArgumentException(implode(PHP_EOL, $errors['errors']));
}
Note :- There could be better solution for this , so if anybody else found its alternative then please share.

Laravel Model Binding missing relationships

I'm trying to convert to Model binding on a Model built on customer orders. My route:
Route::model('order', 'App\Models\Order');
Route::resource('orders', 'OrderController');
This allows me to pull up an Order to edit through my controller (also grabbing statuses to populate a table and passing the logged in user):
public function index(Order $order)
{
$orders = $order->get();
return view('orders.index', compact('orders'));
}
My orders.index will display $order->id properly but when I try to loop through the Actions, which is connected by a hasMany relationship, nothing shows. Or I try to show $order->user->firstname which belongs to User by user_id.
#foreach( $order->actions as $action )
{{ $action->type->type }}
#endforeach
From my Action model:
public function order()
{
return $this->belongsTo('\App\Models\Order', 'order_id');
}
From my Order model:
public function actions()
{
return $this->hasMany('\App\Models\Action', 'order_id');
}
Here's an excerpt from a dump of the Order:
`Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\Models\Order Object
(
[table:protected] => orders
[timestamps] => 1
[dates:protected] => Array
(
[0] => deleted_at
)
[connection:protected] =>
[primaryKey:protected] => id
[perPage:protected] => 15
[incrementing] => 1
[attributes:protected] => Array
(
[id] => 1
[created_at] => 2015-03-16 23:42:45
[updated_at] => 2015-03-19 04:37:53
[deleted_at] =>
[user_id] => 16
[status_id] => 5
[address_id] => 5
[datetime_pickup_actual] =>
[datetime_delivery_actual] =>
[datetime_pickup_requested] => 2015-03-20 17:00:00
[datetime_delivery_requested] => 2015-03-21 17:00:00
[hold] => 0
[weight] => 20
)
[original:protected] => Array
(
[id] => 1
[created_at] => 2015-03-16 23:42:45
[updated_at] => 2015-03-19 04:37:53
[deleted_at] =>
[user_id] => 16
[status_id] => 5
[address_id] => 5
[datetime_pickup_actual] =>
[datetime_delivery_actual] =>
[datetime_pickup_requested] => 2015-03-20 17:00:00
[datetime_delivery_requested] => 2015-03-21 17:00:00
[hold] => 0
[weight] => 20
)
[relations:protected] => Array
(
)
[hidden:protected] => Array
(
)
[visible:protected] => Array
(
)
[appends:protected] => Array
(
)
[fillable:protected] => Array
(
)
[guarded:protected] => Array
(
[0] => *
)
[casts:protected] => Array
(
)
[touches:protected] => Array
(
)
[observables:protected] => Array
(
)
[with:protected] => Array
(
)
[morphClass:protected] =>
[exists] => 1
[forceDeleting:protected] =>
)`
As you compact orders in your controller you should use orders in your Blade template:
#foreach( $orders->actions as $action )
{{ $action->type->type }}
#endforeach
You should be also aware that Order in your index method in controller have nothing in common with Route Model Binding. For index it won't be used at all.
For other methods (show/edit/delete) it won't work because you make a binding with wrong name. It should be:
Route::model('orders', 'App\Models\Order');
and not
Route::model('order', 'App\Models\Order');
Model name (MoneyEntry)
Changed from
Route::resource('moneyentries', 'MoneyEntryController');
to
Route::resource('moneyEntries', 'MoneyEntryController');
Did a trick.

laravel 'Allowed memory size of 134217728 bytes exhausted' on basic query

I have no qlue why I can't get the following to work:
DB::table('twitter_hashtags')->paginate(5);
Every single time I get (the second number tends to differs)
Allowed memory size of 134217728 bytes exhausted (tried to allocate 95735352 bytes)
I tried using as in (18776710), but that did not make any difference
DB::connection()->disableQueryLog();
Removing ->paginate(5) does not make any difference.
When I try:
DB::select('SELECT * FROM twitter_hashtags');
It works fine, but then I can't use the build in the pagination option.
Anyone a suggestion?
The table twitter_hashtags has currently 5500 records. An id, tweet_id and the hashtag are saved, so it can't be the problem that the table is too big.
The table's size:
Data 384,0 KB
Index 464,0 KB
Total 848,0 KB
Update
As requested some more information
This is the action
public function getHashtags()
{
DB::connection()->disableQueryLog(); // With or without does not make a difference
$retweets = DB::table('twitter_hashtags')->paginate(10);
// Show the page
return View::make('twitter/retweets', compact('retweets'));
}
As you see, I use the view of retweets, the problem exits also in retweets, or nearly any other table I try to grab the data from this way.
The 'view'
</pre><? print_r($retweets) ?></pre>
The migration I used to create the table
public function up()
{
Schema::create('twitter_hashtags', function($table)
{
// Basic run information
$table->increments('id');
$table->string('status_id')->index();
$table->string('hashtag')->index();
// Misc.
$table->timestamps();
});
}
These are the first 100 or so lines of the response when raised the memory limit to 256M
Illuminate\Database\Query\Builder Object
(
[connection:protected] => Illuminate\Database\MySqlConnection Object
(
[pdo:protected] => PDO Object
(
)
[queryGrammar:protected] => Illuminate\Database\Query\Grammars\MySqlGrammar Object
(
[wrapper:protected] => `%s`
[selectComponents:protected] => Array
(
[0] => aggregate
[1] => columns
[2] => from
[3] => joins
[4] => wheres
[5] => groups
[6] => havings
[7] => orders
[8] => limit
[9] => offset
[10] => unions
)
[tablePrefix:protected] =>
)
[schemaGrammar:protected] =>
[postProcessor:protected] => Illuminate\Database\Query\Processors\Processor Object
(
)
[events:protected] => Illuminate\Events\Dispatcher Object
(
[container:protected] => Illuminate\Foundation\Application Object
(
[booted:protected] => 1
[bootingCallbacks:protected] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$app] =>
)
)
[1] => Closure Object
(
[static] => Array
(
[instance] => Illuminate\Log\LogServiceProvider Object
(
[defer:protected] => 1
[app:protected] => Illuminate\Foundation\Application Object
*RECURSION*
)
)
)
[2] => Closure Object
(
[static] => Array
(
[instance] => Illuminate\Mail\MailServiceProvider Object
(
[defer:protected] => 1
[app:protected] => Illuminate\Foundation\Application Object
*RECURSION*
)
)
)
[3] => Closure Object
(
[static] => Array
(
[instance] => Illuminate\Queue\QueueServiceProvider Object
(
[defer:protected] => 1
[app:protected] => Illuminate\Foundation\Application Object
*RECURSION*
)
)
)
[4] => Closure Object
(
[static] => Array
(
[instance] => Illuminate\Translation\TranslationServiceProvider Object
(
[defer:protected] => 1
[app:protected] => Illuminate\Foundation\Application Object
*RECURSION*
)
)
)
Update 2
As requested. This is the response:
Array
(
[total] => 5689
[per_page] => 5
[current_page] => 1
[last_page] => 1138
[from] => 1
[to] => 5
[data] => Array
(
[0] => stdClass Object
(
[id] => 1
[status_id] => 384992474579484672
[hashtag] => Twenterand
[created_at] => 2013-10-01 11:00:02
[updated_at] => 2013-10-01 11:00:02
)
[1] => stdClass Object
(
[id] => 2
[status_id] => 384992323190280192
[hashtag] => Twenterand
[created_at] => 2013-10-01 11:00:03
[updated_at] => 2013-10-01 11:00:03
)
[2] => stdClass Object
(
[id] => 3
[status_id] => 384989174014545921
[hashtag] => PVDA
[created_at] => 2013-10-01 11:00:03
[updated_at] => 2013-10-01 11:00:03
)
[3] => stdClass Object
(
[id] => 4
[status_id] => 384988499188801536
[hashtag] => GR2014
[created_at] => 2013-10-01 11:00:03
[updated_at] => 2013-10-01 11:00:03
)
[4] => stdClass Object
(
[id] => 5
[status_id] => 384986184092356608
[hashtag] => GR2014
[created_at] => 2013-10-01 11:00:03
[updated_at] => 2013-10-01 11:00:03
)
)
)
)
)
Update 3
Here the code I use for the getStatuses
public function getStatuses()
{
// Get all the paginated statuses
$statuses = DB::table('twitter_statuses')
->select('status_id', 'text', 'user_screen_name','datetime','place')
->orderBy('datetime', 'DESC')
->paginate(10);
// Show the page
return View::make('twitter/statuses', compact('statuses'));
}
And the complete view file
#extends('layouts/default')
{{-- Page title --}}
#section('title')
Twitter Statuses ::
#parent
#stop
{{-- Page content --}}
#section('content')
<h1>Twitter Statuses</h1>
<div class="container">
<table class="table">
<tr>
<th>Datum</th>
<th>Gebruiker</th>
<th>Tweet</th>
<th>Locatie</th>
</tr>
<?php foreach ($statuses as $status): ?>
<tr>
<td>{{ $status->datetime; }}</td>
<td><?php echo $status->user_screen_name; ?></td>
<td><?php echo $status->text; ?></td>
<td><?php echo $status->place; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $statuses->links(); ?>
</div>
#stop
I just had the same issue. Solution is simple: Just add ->get(); at the end of the query:
public function getStatuses()
{
// Get all the paginated statuses
$statuses = DB::table('twitter_statuses')
->select('status_id', 'text', 'user_screen_name','datetime','place')
->orderBy('datetime', 'DESC')
->paginate(10)
->get()
;
// Show the page
return View::make('twitter/statuses', compact('statuses'));
}

Resources