epowah epowah - 1 month ago 12
PHP Question

Object of class Illuminate\Database\Query\Builder could not be converted to string

I'm making function in controller where I want to attach user and his orders. First I'm making relationship between two models

User
and
Orders
.

This is function in
User
model:

public function orders(){
return $this->belongsToMany('App\Orders', 'user_orders', 'user_id', 'order_id');

}


This is function in
Orders
model:

public function users(){
return $this->belongsToMany('App\User', 'user_orders', 'order_id', 'user_id');
}


This is the new table
user_orders
where I want to attach the user orders with this relationship that I mentioned:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUserOrdersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_orders', function (Blueprint $table) {

$table->increments('id');

/*$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');

$table->integer('order_id')->unsigned();
$table->foreign('order_id')->references('id')->on('orders');*/

$table->integer('user_id');
$table->integer('order_id');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_orders');
}
}


And in the end this is the function where I'm getting the username with request and order id and try to attach the orders to the given user.

public function makeOrder(Request $request, $id){

$user = User::where('name', $request['username'])->first();

$findorder = Orders::find($id);


$user->orders()->detach();
$user->orders()->attach(Orders::where('id', $findorder))->first();


return redirect()->back();

}


I have check also if I'm getting the right user name and order id and the first two lines of the code worked perfect, but when i try to attach the orders I'm getting this error:

ErrorException in Str.php line 289:
Object of class Illuminate\Database\Query\Builder could not be converted to string


Any ideas?

Answer

You should get first object and then get an ID:

$user->orders()->attach(Orders::where('id', $findorder)->first()->id);

You should pass an ID to attach() method, but not a collection or an object.

UPDATE

It seems that $findorder is an order ID, so just do this:

$user->orders()->attach($findorder);
Comments